【问题标题】:Generics with polymorphism and factory class具有多态性和工厂类的泛型
【发布时间】: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&lt;T&gt; 的子类型。我可以将 Factory 类中的返回类型更改为原始类型 GenericInterface,但这似乎不是解决方案,因为那时我在整个项目中都收到了警告。

你对如何实现这样的功能有什么建议吗,也许有不同的设计模式?由于someMethod()的进一步多态调用,我需要通用的超级接口。

【问题讨论】:

  • 你可以在 FactoryClass 中进行强制转换,如下所示:return (GenericInterface&lt;T&gt;) new Class_A();

标签: java generics design-patterns factory-pattern


【解决方案1】:

从你的使用来看,我相信你需要一个类似的界面

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;
    }
}

希望这会有所帮助。
祝你好运。

【讨论】:

  • 不幸的是,类型系统可能无法确定这是类型安全的,并且会发出一些警告甚至错误。
  • 你可能是对的,我没有测试这段代码,只是在这里写的。
  • 我试过了,和Marko说的还是有错误
  • 因此您需要在方法上使用@SuppressWarnings("unchecked"),并在所有情况下使用return (S) new ...。这将对所需的目标类型进行未经检查的强制转换。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-16
  • 2020-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-28
相关资源
最近更新 更多