Effective Java Third edition--3. Implementing the Singleton property using a private construction method or a class

Source: Internet
Author: User

Tips
"Effective Java, third Edition" an English version has been published, the second edition of this book presumably many people have read, known as one of the four major Java books, but the second edition of 2009 published, to now nearly 8 years, but with Java 6, 7, 8, and even 9 of the release, the Java language has undergone profound changes.
In the first time here translated into Chinese version. For everyone to learn to share.

3. Implementing the Singleton property using a private construction method or a class

A singleton is a class that is instantiated only once [Gamma95]. A singleton object typically represents a stateless object, such as a function (entry 24) or a system component that is inherently unique. Making a Class A singleton makes it difficult for the customer to test it because it is not possible to implement an alternative singleton with a simulation unless an interface is implemented as its type.

There are two common ways to implement a singleton. Both are based on preserving the construction method private and exporting public static members to provide access to unique instances. In the first method, the member is a final decorated property:

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

The private constructor method is called only once to initialize the public static final Elvis.INSTANCE property. The absence of a public or protected construction method guarantees global uniqueness: Once the Elvis class is initialized, an instance of Elvis will exist-no more and no less. Nothing the client does can change this, but it is important to note that privileged clients can use AccessibleObject.setAccessible methods to invoke private construction methods in a reflective manner (entry 65). If you need to defend against this attack, modify the constructor so that it throws an exception when the second instance is requested to be created.

In the second method of implementing a singleton, the public member is a static factory method:

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

All pairs Elvis.getInstance of calls return the same object reference, and no other Elvis instances are created (the same as the warning mentioned earlier).

The main advantage of the public property approach is that the API explicitly indicates that the class is a singleton: the public static property is final, so it always contains the same object reference. The second advantage is that it's simpler.

One advantage of the static factory approach is that it has the flexibility to change your mind, whether or not the class is a singleton without having to change its API. The factory method returns a unique instance, but can be modified, for example, to return a separate instance of each thread that called it. A second benefit is that if your application needs it, you can write a generic singleton factory (Generic Singleton Factory) (entry 30). The last advantage of using a static factory is that the method reference can be used supplier , for example, Elvis :: instance equivalent to Supplier<Elvis> . Public property methods are preferable unless they are related to these advantages.

Creating a singleton class that uses both methods (chapter 12th) implements Serializable is not enough to add to the declaration alone. To maintain the singleton guarantee, declare all instance properties as transient , and provide a readResolve method (entry 89). Otherwise, whenever the serialized instance is deserialized, a new instance is created, and in our case, a new Elvis instance occurs. To prevent this from happening, add this readResolve method to the Elvis class:

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

The third way to implement a singleton is to declare an enumeration class of a single element:

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

This approach is similar to public property methods, but is more concise, provides a free serialization mechanism, and provides a robust guarantee against multiple instantiations, even in the case of complex serialization or reflection attacks. This approach may feel a bit unnatural, but a single-element enumeration class is often the best way to implement a singleton . Note that this method cannot be used if the singleton must inherit Enum from a parent class (although one can be declared Enum to implement the interface).

Effective Java Third edition--3. Implementing the Singleton property using a private construction method or a class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.