I have a Data class with several sub-class such as JSONData, XMLData, IntegerData. The task is to process different types of incoming data. So based on program to an interface, not an implementation, I created the following interface with generic type for compile-time type checking:
interface DataProcessor<T extends Data> {
void process(T data);
}
There are several implemenations based on this interface:
* `class JSONDataProcessor implements DataProcessor<JSONData>`
* `class XMLDataProcessor implements DataProcessor<XMLData>`
* `class IntegerDataProcessor implements DataProcessor<IntegerData>`
The rest of the work is to make a simple factory for creating the corresponding DataProcessor instance. So I made the following simple factory, or say it is in fact just a processor mapper as the concrete processor can be cached as static variables inside the ProcessorFactory:
public class ProcessorFactory {
public static DataProcessor<?> create() {
//logic of return an instance
}
}
The design above has a problem - the process method on the returned instance of DataProcessor cannot be called directly:
Data data = jsonData;
ProcessorFactory.create().process(data);
Question: the code above has a compilation error due to the compile-time typing checking as the data has to be the concrete sub-class of Data, how to resolve this? Or is the design per se. bad? if so what would be a better design?