Consider static factory methods instead of constructor
抄襲自《Effective?Java ,Second Edition》
The normal way for a class to allow a client to obtain an instance of itself is to provide a public constructor. There is another technique that should be a part of every
programmer’s toolkit.
例子:Boolean類
public static Boolean valueOf(boolean b) {
return b ? Boolean.TRUE : Boolean.FALSE;
}
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.
A third advantage of static factory methods is that, unlike constructors,
they can return an object of any subtype of their return type.
引用別人文章的一些東西
以下靜態工廠方法的優勢摘自http://blog.csdn.net/dm_vincent/article/details/8513720
靜態工廠方法的優勢
?
當然,這里所說的優勢,通常都是和傳統構造函數相比得到的。
?
靜態工廠方法擁有名字
靜態工廠方法擁有自己的名字,而構造函數則沒有。這也就意味著,同一組參數列表,只能有唯一的一個構造函數(通過改變參數列表中參數的順序,可以有多個構造函數,但是很明顯,這不是一個好主意)。相比之下,靜態工廠方法則沒有這個限制,對同一組參數,可以有任意多的靜態工廠方法。因此,這種情況下使用靜態工廠方法來進行對象實例化更加靈活,可讀性也更好。
?
對于對象實例化的更多控制
對于構造函數而言,一旦它被調用,那么就肯定會生成一個新的實例。而調用靜態工廠方法則不一定,它只需要返回一個對象的實例就夠了,至于這個返回的對象是如何得到的,它并不關注。因此,靜態工廠方法對于對象的實例化就有了更多的控制權。它能夠利用預先創建好的不可變對象(Immutable Instance),也能夠從緩存中獲取某個經常被請求的對象。從而大幅度的提高性能。
英文原文可參照
This
allows immutable classes (Item 15) to use preconstructed instances, or to cache
instances as they’re constructed, and dispense them repeatedly to avoid creating
unnecessary duplicate objects. The Boolean.valueOf(boolean)method illustrates this technique: it never creates an object. This technique is similar to the
Flyweightpattern [Gamma95, p. 195]. It can greatly improve performance if
equivalent objects are requested often, especially if they are expensive to create.
?
返回對象的類型更加泛化
對于構造函數而言,它只能返回當前類的實例。而靜態工廠方法的實際返回類型可以是聲明返回類型的任何子類型。比如,聲明返回Base類型的靜態工廠方法,實際上它能夠返回Sub類型,只要Sub是Base的子類型。因為子類型的概念不僅限于繼承層次,還可以適用在接口和其實現類之間,因此這種泛化的關系也非常契合“面向接口編程”這一指導原則。
轉載于:https://my.oschina.net/liangzhenghui/blog/178187
總結
以上是生活随笔為你收集整理的Consider static factory methods instead of constructor的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: why-use-getters-and-
- 下一篇: 统计学中p值计算公式_不得不学的统计学基