Design patterns represent best practices

The introduction

  • Create pattern.
  • Main features: simple, style.
  • Main solution: a globally used class is frequently created and destroyed.
  • Key code: Constructors are private.

instructions

  • A singleton can have only one instance.
  • A singleton class must create its own unique instance.
  • The singleton class must provide this instance to all other objects.

The advantages and disadvantages

  • Advantages: There is only one instance in memory, reducing memory overhead (frequently created).
  • Disadvantages: No interface, no inheritance, conflicts with the single responsibility principle.

implementation

The hungry

public class Singleton { private static final Singleton instance = new Singleton(); private Singleton() { } public static Singleton getInstance() { return instance; }}Copy the code

Villain mode: no lock, high execution efficiency. However, the class is initialized as soon as it is loaded, which wastes memory and easily generates garbage objects.

lazy

public class Singleton { private static Singleton instance; private Singleton() { } public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; }}Copy the code

Lazy mode: the first call is initialized, solve the memory problem of evil mode. However, synchronization is required every time an instance is acquired, and locking affects efficiency.

Double check

public class Singleton {
    private volatile static Singleton singleton;

    private Singleton() {
    }

    public static Singleton getSingleton() {
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}
Copy the code

Double check mode

  • First nullation: In the case of instantiation (99.99% of the time), synchronization is omitted.
  • Synchronized: ensures thread synchronization during the first instantiation.
  • Second nullation: In the case of multithreading problems encountered in the first instantiation (lock effect scenario), the thread execution after completion of the instantiation is not instantiated again.
  • Volatile: Ensures the order of concurrent scenarios.

Why is order guaranteed?

To create an object, perform the following steps:

  • normal
    • 1. Allocate space
    • 2. The initialization
    • 3. Reference assignment
  • Rearrangement (JIT optimization)
    • 1. Allocate space
    • 2. Reference assignment
    • 3. The initialization

In the scenario of single thread model, instruction reordering does not affect the execution result. JIT instruction rearrangement optimizations do not consider concurrent scenarios. From the reordering sequence above, you can see why volatile is used to ensure order. The singleton reference is no longer empty but has not been initialized. The calling thread will get an uninitialized reference to make a method call and crash abnormally.

Ps: If you want to see how to create an object, run the following command:

  • Generate bytecode files: javac xx.java;
  • Disassemble the generated bytecode files: javap -c -v xx.class;
  • Through assembly instructions and constant pool serial number, corresponding to search.

Static inner class

public class Singleton { private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } private Singleton() { } public static final Singleton getInstance() { return SingletonHolder.INSTANCE; }}Copy the code

Static inner class pattern: Implementation is simpler.

The enumeration

public enum Singleton {
    INSTANCE;

    public void todo() {
    }
}
Copy the code

Enumeration pattern: The best way to implement the singleton pattern. More concise, automatic support serialization mechanism, to prevent deserialization. The downside is poor readability (this thing doesn’t look like a singleton at all).

Summary of implementation

Xiaobian blog series

Design pattern family bucket