jeudi 29 janvier 2015

Generics with polymorphism and factory class

I made few classes structure and now I have problem with creating them in my factory class. I have generic interface:



interface GenericInterface<T>{
T someMethod();
}


And subclasses like:



class Class_A implements GenericInterface<String>{
String someMethod(){//impl};
}

class Class_B implements GenericInterface<Integer>{
Integer someMethod(){//impl};
}


Now the problem is that I need factory class like:



class FactoryClass{
static <T> GenericInterface<T> getSpecificClass(T instance){
//errors
if(T instanceof String) return new Class_A;
if(T instanceof Integer) return new Class_B;
}


and somewhere else:



String test = "some text";
GenericInterface<T> helper = FactoryClass.getSpecificClass(test);
String afterProcessing = helper.someMethod(test);


So for String object as a parameter I should get the Class_A instance and for Integer the Class_B instance. Now I have an error that Class_A is not subtype of GenericInterface<T>. I can change the return type in Factory class to raw type GenericInterface but it does not seem to be solution since I've got warnings all over the project then.


Do You have any suggestions how to achieve such functionality, maybe with different design pattern? I need common super interface because of further polymorphic calls of someMethod().


Aucun commentaire:

Enregistrer un commentaire