question:這個(gè)方法實(shí)際上并不返回一個(gè)object?
對的, sun的jdk 幫助里面講: If a new Boolean instance is not required, this method should generally be used in preference to the constructor Boolean(boolean).
但是,不是說(shuō)靜態(tài)工廠(chǎng)方法所有時(shí)候都不返回一個(gè)object,只是不是所有時(shí)候都返回一個(gè)object。
使用靜態(tài)工廠(chǎng)方法和構造方法比較的優(yōu)缺點(diǎn):
優(yōu)點(diǎn):
1. 靜態(tài)工廠(chǎng)方法都是有自己的名字,容易理解.
2. 靜態(tài)工廠(chǎng)方法并不要求每次都生成一個(gè)對象.比如上面提到的Boolean的public static Boolean valueOf(boolean b)就不會(huì )返回一個(gè)object. sun的jdk幫助文檔里面也提到,在不需要得到一個(gè)對象的情況下,使用valueof方法可以得到性能的提升.
而且這樣,可以控制類(lèi)在生的期間該類(lèi)的句柄數,這個(gè)作用在單態(tài)(item 21)和類(lèi)型安全(item 21)都是有用的.
3. 靜態(tài)工廠(chǎng)方法可以返回該類(lèi)的任何子類(lèi),這給了程序員更大的選擇空間.
比如Collections,用了很多靜態(tài)工廠(chǎng)方法來(lái)得到immuable的set,map之類(lèi)的.
而且靜態(tài)工廠(chǎng)方法可以強迫user通過(guò)接口來(lái)引用被返回的對象,而不是每次都使用構造函數,這是一個(gè)好習慣.
靜態(tài)工廠(chǎng)方法返回的類(lèi),在編寫(xiě)含有靜態(tài)工廠(chǎng)方法這個(gè)類(lèi)的時(shí)候,可以并不存在,這就提供了一種靈活的service provider framework.比如java的密碼系統擴展(JCE),provider為user提供多個(gè)api實(shí)現,framework提供一種機制來(lái)register這些實(shí)現,用戶(hù)只需直接使用api,而不用考慮自己在使用哪個(gè)實(shí)現。
下面是這種機制的程序框架:
[code]import java.util.*;
// Provider framework sketch
public abstract class Foo {
// Maps String key to corresponding Class object
private static Map implementations = null;
// Initializes implementations map the first time it‘s called
private static synchronized void initMapIfNecessary() {
if (implementations == null) {
implementations = new HashMap();
// Load implementation 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)
return new DefaultFoo();
try {
return (Foo) c.newInstance();
} catch (Exception e) {
return new DefaultFoo();
}
}
public static void main(String[] args) {
System.out.println(getInstance("NonexistentFoo"));
}
}
class DefaultFoo extends Foo {
}[/code]
靜態(tài)工廠(chǎng)方法的缺點(diǎn):
1. 僅僅有靜態(tài)工廠(chǎng)方法而沒(méi)有public的構造方法的類(lèi)不能被繼承…這也不是沒(méi)有好處--可能能迫使程序員使用復合來(lái)代替繼承.
2. 有時(shí)候可能會(huì )導致與其他的static方法混淆.這個(gè)缺點(diǎn)可以通過(guò)使用標準的命名方法來(lái)區別于其他的static方法.
現在有兩種方法已經(jīng)開(kāi)始形成標準:
valueof(type k)-返回和k有相同值的句柄.
Getinstance-返回一個(gè)復合參數所描述的句柄.但是不一定和參數具有相同的值..這個(gè)方法在Provider framework里面是很有用的.
所以,我們不要每次都毫不猶豫的使用構造方法,有時(shí)候靜態(tài)工廠(chǎng)方法可能是更加合適的.但是當你無(wú)法取舍的時(shí)候,還是使用構造方法吧,因為它是比較普通和標準的.
聯(lián)系客服