我最近遇到了以下模式的一个实例:
public interface IFooFactory {
<K> Foo<K> create();
}
有关具体示例,请参见此处。除了使用Object的正式类型参数或根本没有正式类型参数来实例化Foo之外,我看不到客户端程序员在create的实现中应该做什么。我也看不出框架设计者试图通过以这种方式定义接口IFooFactory来表达什么好处或类型约束。
好处是给方法的用户,而不是实现者。Collections.emptyList()
是对这种模式的有益使用的一个很好的例子。它允许您像这样声明一个空列表:
List<String> myEmptyList = Collections.emptyList();
如果该方法返回一个 raw List
,List<Object>
或List<?>
, 以这种方式使用该方法将需要强制转换。
考虑Collections.emptyList()
。返回的列表对象始终是相同的:由于列表是空的且不可变的,因此调用者无法对返回的对象执行任何操作,以使其根据替代类型参数的具体类型显示不同的行为。因此,单个实现(使用原始类型)就足够了:
public static <T> List<T> emptyList() {
return THEEMPTYLIST;
}
public static final List THEEMPTYLIST = new List() {
public int size() { return 0; }
...
};
但是,该emptyList
方法使调用者更方便,因为它启用了类型推断:
List<String> noStrings = Collections.EMPTY; // Gives compiler warning due to use of raw types
List<String> noStrings2 = Collections.emptyList(); // No compiler warning, type parameter inferred.
I don't see what a client programmer is supposed to do in the implementation of create other than instantiate Foo with a formal type parameter of Object or with no formal type parameter at all.
Umm... It's very easy...
<K> Foo<K> create() {
return new Foo<K>();
}