静态工厂方法:实际上只是一个简单的静态方法,它返回的类的实例。
示例:public static void Boolean valueOf(boolean b){
return toBoolean(s) ? TRUE : FALSE;
}
private static boolean toBoolean(String name) {
return ((name != null) && name.equalsIgnoreCase("true"));
}
优点:1。静态工厂方法具有名字——〉使代码容易阅读。
2.每次调用时,不要求非得创建一个新的对象——〉免去创建对象的代价;可以为重复的调用返回同一个对象,(保证 singleton;保证当且仅当a==b时才有a.equals(b)为true),如String.intern()方法
3.可以返回一个原返回类型的字类型的对象——〉在选择被返回对象的类型时有了更大的灵活性(应用:一个API可以返回一个对象,同时右不使该对象的类成为公有的,这样可以把具体的实现类隐藏起来,得到一个简洁的API)。如Collections Framework有20个实用的集合接口实现,这些实现绝大多数都是通过一个不可实例化的类中的静态工厂方法而被导出的,所有返回对象的类都不是公有的。
缺点:1。类如果不含有公有的或保护的构造函数,——〉就不能被子类化。如要想子类化Collections Framework中的任何一个方便的实现类,是不可能的。
2.它们与其它静态方法没有任何区别。——〉对规范的背离(流行的静态工厂方法命名:valueOf,getInstance)
import java.util.*;
//Provider framework sketch
publicabstractclass Foo {
//Maps String key to corresponding Class object
privatestatic Map implementations = null;
//Initializes implementations map the first time it's called
privatestaticsynchronizedvoid initMapIfNecessary(){
if (implementations == null){
implementations = new HashMap();
//Load implementations class names and keys from
//Properties file,translate names into Class
//objects using Class.forName and store mappings.
//...
}
}
public static Foo getInstance(String key){
initMapIfNecessary();
Class c =(Class)implementations.get(key);
if (c==null)
returnnew DefaultFoo();
try{
return (Foo)c.newInstance();
}catch(Exception e){
returnnew DefaultFoo();
}
}
//entry
publicstaticvoid main(String[] args) {
System.out.println(getInstance("NonexistentFoo"));
}
}
class DefaultFoo extends Foo{}