Item 3: Enforce the singleton property with a private constructor or an enum type(使用私有構(gòu)造函數(shù)或枚舉類(lèi)型實(shí)施...

A singleton is simply a class that is instantiated(v.實(shí)例化) exactly once [Gamma95].Singletons typically represent either a stateless object such as a function (Item24) or a system component that is intrinsically unique. Making a class a singleton can make it difficult to test its clients because it’s impossible to substitute a mock implementation for a singleton unless it implements an interface that serves as its type.

單例是一個(gè)只實(shí)例化一次的類(lèi) [Gamma95]跟磨。單例通常表示無(wú)狀態(tài)對(duì)象,比如函數(shù)(Item-24)或系統(tǒng)組件彭则,它們?cè)诒举|(zhì)上是唯一的。將一個(gè)類(lèi)設(shè)計(jì)為單例會(huì)使它的客戶端測(cè)試時(shí)變得困難, 除非它實(shí)現(xiàn)了作為其類(lèi)型的接口酱塔,否則無(wú)法用模擬實(shí)現(xiàn)來(lái)代替單例绳矩。

There are two common ways to implement singletons. Both are based on keeping the constructor private and exporting a public static member to provide access to the sole instance. In one approach, the member is a final field:

實(shí)現(xiàn)單例有兩種常見(jiàn)的方法驮捍。兩者都基于保持構(gòu)造函數(shù)私有和導(dǎo)出公共靜態(tài)成員以提供對(duì)唯一實(shí)例的訪問(wèn)。在第一種方法中脚曾,成員是一個(gè) final 字段:

// Singleton with public final field
public class Elvis {
    public static final Elvis INSTANCE = new Elvis();
    private Elvis() { ... }
    public void leaveTheBuilding() { ... }
}

The private constructor is called only once, to initialize the public static final field Elvis.INSTANCE. The lack of a public or protected constructor guarantees a “monoelvistic” universe: exactly one Elvis instance will exist once the Elvis class is initialized—no more, no less. Nothing that a client does can change this, with one caveat: a privileged client can invoke the private constructor reflectively (Item 65) with the aid of the AccessibleObject.setAccessible method. If you need to defend against this attack, modify the constructor to make it throw an exception if it’s asked to create a second instance.

私有構(gòu)造函數(shù)只調(diào)用一次东且,用于初始化 public static final 修飾的 Elvis 類(lèi)型字段 INSTANCE。不使用 public 或 protected 的構(gòu)造函數(shù)保證了「獨(dú)一無(wú)二」的空間:一旦初始化了 Elvis 類(lèi)本讥,就只會(huì)存在一個(gè) Elvis 實(shí)例珊泳,不多也不少】椒校客戶端所做的任何事情都不能改變這一點(diǎn)色查,但有一點(diǎn)需要注意:擁有特殊權(quán)限的客戶端可以借助 AccessibleObject.setAccessible 方法利用反射調(diào)用私有構(gòu)造函數(shù)(Item-65)如果需要防范這種攻擊,請(qǐng)修改構(gòu)造函數(shù)撞芍,使其在請(qǐng)求創(chuàng)建第二個(gè)實(shí)例時(shí)拋出異常秧了。

譯注:使用 AccessibleObject.setAccessible 方法調(diào)用私有構(gòu)造函數(shù)示例:

Constructor<?>[] constructors = Elvis.class.getDeclaredConstructors();
AccessibleObject.setAccessible(constructors, true);

Arrays.stream(constructors).forEach(name -> {
    if (name.toString().contains("Elvis")) {
        Elvis instance = (Elvis) name.newInstance();
        instance.leaveTheBuilding();
    }
});

In the second approach to implementing singletons, the public member is a static factory method:

在實(shí)現(xiàn)單例的第二種方法中,公共成員是一種靜態(tài)工廠方法:

// Singleton with static factory
public class Elvis {
    private static final Elvis INSTANCE = new Elvis();
    private Elvis() { ... }
    public static Elvis getInstance() { return INSTANCE; }
    public void leaveTheBuilding() { ... }
}

All calls to Elvis.getInstance return the same object reference, and no other Elvis instance will ever be created (with the same caveat(n.警告) mentioned(v.提到) earlier).

所有對(duì) getInstance() 方法的調(diào)用都返回相同的對(duì)象引用序无,并且不會(huì)創(chuàng)建其他 Elvis 實(shí)例(與前面提到的警告相同)验毡。

譯注:這里的警告指擁有特殊權(quán)限的客戶端可以借助 AccessibleObject.setAccessible 方法利用反射調(diào)用私有構(gòu)造函數(shù)

The main advantage of the public field approach is that the API makes it clear that the class is a singleton: the public static field is final, so it will always contain the same object reference. The second advantage is that it’s simpler.

公共字段方法的主要優(yōu)點(diǎn)是 API 明確了類(lèi)是單例的:public static 修飾的字段是 final 的,因此它總是包含相同的對(duì)象引用帝嗡。第二個(gè)優(yōu)點(diǎn)是更簡(jiǎn)單晶通。

One advantage of the static factory approach is that it gives you the flexibility to change your mind about whether the class is a singleton without changing its API. The factory method returns the sole instance, but it could be modified to return, say, a separate instance for each thread that invokes it. A second advantage is that you can write a generic singleton factory if your application requires it (Item 30). A final advantage of using a static factory is that a method reference can be used as a supplier, for example Elvis::instance is a Supplier<Elvis>. Unless one of these advantages is relevant, the public field approach is preferable.

譯注:static factory approach 等同于 static factory method

靜態(tài)工廠方法的一個(gè)優(yōu)點(diǎn)是,它可以在不更改 API 的情況下決定類(lèi)是否是單例哟玷。工廠方法返回唯一的實(shí)例狮辽,但是可以對(duì)其進(jìn)行修改,為調(diào)用它的每個(gè)線程返回一個(gè)單獨(dú)的實(shí)例巢寡。第二個(gè)優(yōu)點(diǎn)是喉脖,如果應(yīng)用程序需要的話,可以編寫(xiě)泛型的單例工廠(Item-30)讼渊。使用靜態(tài)工廠的最后一個(gè)優(yōu)點(diǎn)是方法引用能夠作為一個(gè)提供者动看,例如 Elvis::getInstanceSupplier<Elvis> 的提供者。除非能夠與這些優(yōu)點(diǎn)沾邊爪幻,否則使用 public 字段的方式更可取菱皆。

譯注 1:原文方法引用可能是筆誤,修改為 Elvis::getInstance

譯注 2:方法引用作為提供者的例子:

Supplier<Elvis> sup = Elvis::getInstance;
Elvis obj = sup.get();
obj.leaveTheBuilding();

To make a singleton class that uses either of these approaches serializable (Chapter 12), it is not sufficient merely to add implements Serializable to its declaration. To maintain(vt.維持) the singleton guarantee(n.保證), declare all instance fields transient and provide a readResolve method (Item 89). Otherwise, each time a serialized instance is deserialized, a new instance will be created, leading,in the case of our example, to spurious(adj.虛假的) Elvis sightings. To prevent this from happening, add this readResolve method to the Elvis class:

要使單例類(lèi)使用這兩種方法中的任何一種(Chapter 12)挨稿,僅僅在其聲明中添加實(shí)現(xiàn) serializable 是不夠的仇轻。要維護(hù)單例保證,應(yīng)聲明所有實(shí)例字段為 transient奶甘,并提供 readResolve 方法(Item-89)篷店。否則,每次反序列化實(shí)例時(shí),都會(huì)創(chuàng)建一個(gè)新實(shí)例疲陕,在我們的示例中方淤,這會(huì)導(dǎo)致出現(xiàn)虛假的 Elvis。為了防止這種情況發(fā)生蹄殃,將這個(gè) readResolve 方法添加到 Elvis 類(lèi)中:

// readResolve method to preserve singleton property
private Object readResolve() {
    // Return the one true Elvis and let the garbage collector
    // take care of the Elvis impersonator.
    return INSTANCE;
}

A third way to implement a singleton is to declare a single-element enum:

實(shí)現(xiàn)單例的第三種方法是聲明一個(gè)單元素枚舉:

// Enum singleton - the preferred approach
public enum Elvis {
    INSTANCE;
    public void leaveTheBuilding() { ... }
}

This approach(n.方法携茂,途徑;vt.接近) is similar to the public field approach, but it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. This approach may feel a bit unnatural, but a single-element enum type is often the best way to implement a singleton. Note that you can’t use this approach if your singleton must extend a superclass other than Enum(though you can declare an enum to implement interfaces).

這種方法類(lèi)似于 public 字段方法诅岩,但是它更簡(jiǎn)潔讳苦,默認(rèn)提供了序列化機(jī)制,提供了對(duì)多個(gè)實(shí)例化的嚴(yán)格保證吩谦,即使面對(duì)復(fù)雜的序列化或反射攻擊也是如此鸳谜。這種方法可能有點(diǎn)不自然,但是單元素枚舉類(lèi)型通常是實(shí)現(xiàn)單例的最佳方法式廷。 注意咐扭,如果你的單例必須擴(kuò)展一個(gè)超類(lèi)而不是 Enum(盡管你可以聲明一個(gè) Enum 來(lái)實(shí)現(xiàn)接口),你就不能使用這種方法懒棉。


Back to contents of the chapter(返回章節(jié)目錄)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市策严,隨后出現(xiàn)的幾起案子穗慕,更是在濱河造成了極大的恐慌,老刑警劉巖妻导,帶你破解...
    沈念sama閱讀 218,284評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件逛绵,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡倔韭,警方通過(guò)查閱死者的電腦和手機(jī)术浪,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)寿酌,“玉大人胰苏,你說(shuō)我怎么就攤上這事〈继郏” “怎么了硕并?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,614評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)秧荆。 經(jīng)常有香客問(wèn)我倔毙,道長(zhǎng),這世上最難降的妖魔是什么乙濒? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,671評(píng)論 1 293
  • 正文 為了忘掉前任陕赃,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘么库。我一直安慰自己傻丝,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,699評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布诉儒。 她就那樣靜靜地躺著桑滩,像睡著了一般。 火紅的嫁衣襯著肌膚如雪允睹。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,562評(píng)論 1 305
  • 那天幌氮,我揣著相機(jī)與錄音缭受,去河邊找鬼。 笑死该互,一個(gè)胖子當(dāng)著我的面吹牛米者,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播宇智,決...
    沈念sama閱讀 40,309評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼蔓搞,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了随橘?” 一聲冷哼從身側(cè)響起喂分,我...
    開(kāi)封第一講書(shū)人閱讀 39,223評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎机蔗,沒(méi)想到半個(gè)月后蒲祈,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,668評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡萝嘁,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,859評(píng)論 3 336
  • 正文 我和宋清朗相戀三年梆掸,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片牙言。...
    茶點(diǎn)故事閱讀 39,981評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡酸钦,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出咱枉,到底是詐尸還是另有隱情卑硫,我是刑警寧澤,帶...
    沈念sama閱讀 35,705評(píng)論 5 347
  • 正文 年R本政府宣布庞钢,位于F島的核電站拔恰,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏基括。R本人自食惡果不足惜颜懊,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,310評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧河爹,春花似錦匠璧、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,904評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至媳维,卻和暖如春酿雪,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背侄刽。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,023評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工指黎, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人州丹。 一個(gè)月前我還...
    沈念sama閱讀 48,146評(píng)論 3 370
  • 正文 我出身青樓醋安,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親墓毒。 傳聞我的和親對(duì)象是個(gè)殘疾皇子吓揪,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,933評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,332評(píng)論 0 10
  • 致青春 ――我們都有各自的精彩 此刻,我講的是他的故事所计,占據(jù)我整個(gè)青春一大半的他孤獨(dú)的日子柠辞。...
    淺子草閱讀 297評(píng)論 0 0
  • 希望每次都能有進(jìn)步喲。 很想試試這幅風(fēng)景圖片醉箕,會(huì)不會(huì)很失望……
    蘭花草的夢(mèng)閱讀 341評(píng)論 1 2