一般客戶端訪問(wèn)類實(shí)例的方式是使用一個(gè)public的構(gòu)造函數(shù)。但是也可以使用一個(gè)public的static factory method,它只是一個(gè)返回類實(shí)例的簡(jiǎn)單靜態(tài)方法。注意static factory method不同于設(shè)計(jì)模式中的Factory Method。static factory method的例子如Boolean類中下面代碼:
public static Boolean valueOf(boolean b) {
return b ? Boolean.TRUE : Boolean.FALSE;
}
可以用static factory method代替構(gòu)造函數(shù),也可以同時(shí)使用兩者。用static factory method代替構(gòu)造函數(shù)的好處是:
1.不同于構(gòu)造函數(shù),靜態(tài)工廠方法可以靈活命名。
2.不同于構(gòu)造函數(shù),靜態(tài)工廠方法不需要每次在調(diào)用的時(shí)候創(chuàng)建一個(gè)新對(duì)象。
3.不同于構(gòu)造函數(shù),靜態(tài)工廠方法可以返回返回類型的任何子類型。
4.使用靜態(tài)工廠方法減少了創(chuàng)建參數(shù)類型實(shí)例的繁瑣。
使用static factory method的缺點(diǎn)是:
1.如果僅僅提供靜態(tài)工廠方法,而不提供public或者protected構(gòu)造函數(shù)的話,那么構(gòu)造函數(shù)就不能被子類型化。
2.靜態(tài)工廠方法很容易同其他靜態(tài)方法混淆在一起。
結(jié)論:
In summary, static factory methods and public constructors both have their
uses, and it pays to understand their relative merits. Often static factories are preferable,
so avoid the reflex to provide public constructors without first considering
static factories.
靜態(tài)工廠方法和public的構(gòu)造函數(shù)都有自己的用法,需要理解各自的相關(guān)優(yōu)缺點(diǎn)。通常靜態(tài)工廠方法是比較合適的選擇。因此在首先不考慮靜態(tài)工廠方法的時(shí)候因避免提供public構(gòu)造函數(shù)所帶來(lái)的影響。