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::getInstance
是 Supplier<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)接口),你就不能使用這種方法懒棉。