[Effective Java] Item 3: Enhancing singleton properties with private constructors or enumeration types

Objects decorated by Singleton are unique in the system.

Implementation of Singleton

public domain method

public class SingletonTestOne {
    public static final SingletonTestOne INSTANCE = new SingletonTestOne();

    private SingletonTestOne() {

    }

    public void printMsg () {
        System.out.println("This is Singleton One");
    }
}

factory method

public class SingletonTestTwo {
    private static final SingletonTestTwo INSTANCE = new SingletonTestTwo();

    private SingletonTestTwo() {

    }

    public static SingletonTestTwo getInstance() {
        return INSTANCE;
    }

    public void printMsg () {
        System.out.println("This is Singleton two");
    }
}

Factory methods compared to public domain methods: Factory methods have higher flexibility. It is possible to change the idea of ​​whether the class should be a Singleton without changing the API (for example, make the factory method return an instance on a per-thread basis).

In order for the singleton method to support serialization, it is only added on the class implements Serializable, and the method needs to be overridden readSolve. As follows:

public class SingletonTest implements Serializable {

  private static final SingletonTest instance = new SingletonTest();

  private SingletonTest() {}

  public static SingletonTest getInstance() {
    return instance;
  }

  //返回instance对象,否则反序列化时每次都会新建个对象
  private Object readResolve() {
    return instance;
  }
}

Enum method (recommended)

public enum SingletonTestEnum {
    INSTANCE;

    public void printMsg() {
        System.out.println("This is Singleton enum");
    }
}

The class is concise and supports serialization, so you don't have to worry about generating multiple objects during deserialization.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325950161&siteId=291194637