日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Consider static factory methods instead of constructor

發布時間:2025/3/15 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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類型,只要SubBase的子類型。因為子類型的概念不僅限于繼承層次,還可以適用在接口和其實現類之間,因此這種泛化的關系也非常契合“面向接口編程”這一指導原則。

轉載于:https://my.oschina.net/liangzhenghui/blog/178187

總結

以上是生活随笔為你收集整理的Consider static factory methods instead of constructor的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。