【发布时间】:2015-01-29 10:40:02
【问题描述】:
我做了几个类结构,现在我在我的工厂类中创建它们时遇到了问题。 我有通用接口:
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);
所以对于 String 对象作为参数,我应该得到 Class_A 实例,对于 Integer,我应该得到 Class_B 实例。
现在我有一个错误,Class_A 不是GenericInterface<T> 的子类型。我可以将 Factory 类中的返回类型更改为原始类型 GenericInterface,但这似乎不是解决方案,因为那时我在整个项目中都收到了警告。
你对如何实现这样的功能有什么建议吗,也许有不同的设计模式?由于someMethod()的进一步多态调用,我需要通用的超级接口。
【问题讨论】:
-
你可以在 FactoryClass 中进行强制转换,如下所示:
return (GenericInterface<T>) new Class_A();
标签: java generics design-patterns factory-pattern