靜態Factory 方法:實際上只是一個簡單的靜態方法,它返回的類的執行個體。
樣本: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。靜態Factory 方法具有名字——〉使代碼容易閱讀。
2.每次調用時,不要求非得建立一個新的對象——〉免去建立對象的代價;可以為重複的調用返回同一個對象,(保證 singleton;保證若且唯若a==b時才有a.equals(b)為true),如String.intern()方法
3.可以返回一個原傳回型別的字類型的對象——〉在選擇被返回對象的類型時有了更大的靈活性(應用:一個API可以返回一個對象,同時右不使該對象的類成為公有的,這樣可以把具體的實作類別隱藏起來,得到一個簡潔的API)。如Collections Framework有20個實用的集合介面實現,這些實現絕大多數都是通過一個不可執行個體化的類中的靜態Factory 方法而被匯出的,所有返回對象的類都不是公有的。
缺點:1。類如果不含有公有的或保護的建構函式,——〉就不能被子類化。如要想子類化Collections Framework中的任何一個方便的實作類別,是不可能的。
2.它們與其它靜態方法沒有任何區別。——〉對規範的背離(流行的靜態Factory 方法命名: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{}