天天看點

Effective Java——Item 1: Consider static factory methods instead of constructors

Item 1: Consider static factory methods instead of constructors 考慮用靜态的工廠方法來代替構造函數

One advantage of static factory methods is that, unlike constructors, they

have names.

好處之一是,不像構造函數隻能以類名命名,靜态的工廠方法可以有自己的名字,這增加了程式的可讀性

A second advantage of static factory methods is that, unlike constructors,

they are not required to create a new object each time they’re invoked.

好處之二是,不像構造函數每次調用創造出一個新的對象,靜态的工廠方法并不是必須傳回一個新的對象。

利用這一特點,靜态工廠方法可用來建立以下類的執行個體:

1)單例(Singleton)類:隻有惟一的執行個體的類。比如說加載配置檔案

把構造方法定義為private類型,提供public static類型的靜态工廠方法,例如:

public class GlobalConfig {

private static final GlobalConfig INSTANCE =new GlobalConfig();

private GlobalConfig() {…}

public static GlobalConfig getInstance(){return INSTANCE;}

}

2)枚舉類:執行個體的數量有限的類。

枚舉類是指執行個體的數目有限的類,比如表示性别的Gender類,它隻有兩個執行個體:Gender.FEMALE和Gender.MALE。在建立枚舉類時,可以考慮采用以下設計模式:

1)把構造方法定義為private類型。

2)提供一些public static final類型的靜态變量,每個靜态變量引用類的一個執行個體。

3) 如果需要的話,提供靜态工廠方法,允許使用者根據特定參數獲得與之比對的執行個體。

A third advantage of static factory methods is that, unlike constructors,

they can return an object of any subtype of their return type.

好處之三是,不像構造函數隻能傳回本類型的執行個體,靜态工廠方法可以傳回子類型的對象執行個體。

這個特性可以應用于實作松耦合的接口

public static Shape getShape(int type){…}

以上方法聲明的傳回類型是Shape類型,實際上傳回的是Shape子類的執行個體。對于Shape類的使用者Panel類,隻用通路Shape類,而不必通路它的子類:

//獲得一個Circle執行個體

Shape shape=ShapeFactory.getInstance(ShapeFactory.SHAPE_TYPE_CIRCLE);

A fourth advantage of static factory methods is that they reduce the verbosity

of creating parameterized type instances.

好處之四是,靜态工廠方法可以替代有着冗長的參數清單的構造函數。

Map<String, List<String>> m =

new HashMap<String, List<String>>();

可以被以下靜态工廠方法替代

public static <K, V> HashMap<K, V> newInstance() {

return new HashMap<K, V>();

}

Map<String, List<String>> m = HashMap.newInstance();

The main disadvantage of providing only static factory methods is that

classes without public or protected constructors cannot be subclassed.

害處之一是,如果隻提供靜态工廠類方法而不提供public或者protected的構造函數,那麼這個類将不能被子類化

A second disadvantage of static factory methods is that they are not

readily distinguishable from other static methods.

害處之二是,靜态工廠方法不能很明顯的和其他靜态方法差別開來

以下是一些常用的靜态工廠方法名稱:

valueOf ——類型轉換

of ——valueOf()的簡明寫法

getInstance ——傳回執行個體

newInstance ——傳回一個新的執行個體

getType ——傳回一個對象,不是和該類同一類型

newType ——傳回一個新的對象