我制作了几个类结构,现在我在工厂类中创建它们时遇到了问题。 我有通用接口(interface):
interface GenericInterface<T>{
T someMethod(T instance);
}
还有像这样的子类:
class Class_A implements GenericInterface<String>{
String someMethod(String instance){//impl};
}
class Class_B implements GenericInterface<Integer>{
Integer someMethod(Integer instance){//impl};
}
现在的问题是我需要这样的工厂类:
class FactoryClass{
static <T> GenericInterface<T> getSpecificClass(T instance){
//errors
if(instance instanceof String) return new Class_A;
if(instance instanceof Integer) return new Class_B;
}
还有其他地方:
String test = "some text";
GenericInterface<String> helper = FactoryClass.getSpecificClass(test);
String afterProcessing = helper.someMethod(test);
所以对于作为参数的字符串对象,我应该得到 Class_A
实例和整数 Class_B
实例。
现在我有一个错误 Class_A
不是 GenericInterface<T>
的子类型.我可以将 Factory 类中的返回类型更改为原始类型 GenericInterface
但这似乎不是解决方案,因为那时我在整个项目中都收到了警告。
您对如何使用不同的设计模式实现此类功能有什么建议吗?由于 someMethod()
的进一步多态调用,我需要通用 super 接口(interface).
最佳答案
根据您的使用情况,我相信您需要一个类似的界面
interface GenericInterface<T>{
T someMethod(T input);
}
现在,你应该有这样的工厂类了
class FactoryClass {
static <T, S extends GenericInterface<T>> S getSpecificClass(T instance) {
if(instance instanceof String) return new Class_A();
if(instance instanceof Integer) return new Class_B();
return null;
}
}
希望这对您有所帮助。
祝你好运。
关于java - 具有多态性和工厂类的泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28212585/