Java Effective Summary — 静态工厂方法
静态工厂方法的格式
类型0:public static returnType methodName( parameters… )
类型1(泛型):public static typeVariable returnType methodName( parameters.. )
Notes:
0) 一定是以public static开头;
1) 一定要有返回类型,即有返回值和return关键字;
2) 参数有无视情况而定。
// Example 0:
public static Boolean valueOf(boolean b){
return b ? Boolean.TRUE : Boolean.FALSE;
}
// Example 1:
public static <K, V> HashMap<K, V> newInstance(){
return new HashMap<K, V>();
}
优点
注意:都是相较于构造器而言。
优点1:静态工厂方法有自己的方法名字,而构造器的名字必须和类名一致;另外,对于相同的签名的构造器,可以用静态工厂方法代替;
优点2:可以不创建新的对象,例如Example 0;
优点3:可以返回任何子类的对象;例如Collections中的静态工厂方法:
// Retruns an unmodifiable view of the specified set.
public static <T> Set<T> unmodifeableSet(Set<? extends T> s){
return new UnmodifiableSet<>(s);
}
static class UnmodifiableSet<E> entends UnmodifableCollection<E> implements Set<E>, Seriablizable{
...
}
优点4:结合泛型,创建参数化实例,使代码更简洁,例如Example 1。
缺点
缺点1:如果构造器不是public或者protected,则不能子类化(subclass);
public class Collections {
private Collections{
}
...
}
缺点2:很难与其他的静态方法区分。
静态工厂方法的一些惯用名称
+valueOf
+of
+getInstance
+newInstance
+getType
+newType