【发布时间】:2015-04-17 10:26:52
【问题描述】:
参考下面的代码 sn-p,我有一个接口Splitter,它接受泛型类型参数T 和V。有一种实现是CompanySplitterImpl。可能有很多这样的实现。
public interface Splitter<T, V> {
V[] split(T arg);
}
public class CompanySplitterImpl
implements Splitter<Company, Department> {
@Override
public Department[] split(Company comp) {
return comp.getDepartment();
}
}
我正在尝试编写一个工厂方法,它根据传入工厂方法的关键参数值返回不同的实现。
// Factory method to return different Implementation of Splitter
// (Is Splitter return type correct?)
public static Splitter getSplitter(String key) {
return new CompanySplitterImpl(); // Is this correct?
}
我的问题是返回Splitter<K, V>的不同实现实例的正确方式是什么?
// Client to call factory method...
// Not sure what will be type argument for Splitter type
Splitter<?> split = getSplitter("dummyKey");
在客户端,Splitter 类型的类型参数是什么?
【问题讨论】:
-
您是否认同使用
String作为密钥的想法?请注意,Splitter是 raw type,可能不是一个好主意。您正在失去类型安全性。相关:"Avoid unchecked assignment in a map with multiple value types?" -
另外,你应该尽量避免使用泛型类型的数组——改用
List<V>。原因有点复杂,但基本上泛型可以很容易地避免泛型的类型安全优势。 -
CompanySplitterImpl是Splitter<Company, Department>,正如您定义的那样。
标签: java generics return-type