The singleton pattern

The hungry type

Privatize the constructor

Class to create objects inside

Expose a static public method

// Static variable
class Singleton {
    //
    private Singleton(a) {}private final static Singleton intance = new Singleton();

    public static Singleton getIntance(a) {
        returnintance; }}Copy the code

May cause memory waste

// Static code block
class Singleton {
    // Privatize the constructor
    private Singleton(a) {}private static Singleton intance;

    static {
        intance = new Singleton();
    }

    public static Singleton getIntance(a) {
        returnintance; }}Copy the code

LanHanShi

Private static Singleton instance; private static Singleton instance; Public static Singleton getInstance() {if (instance == null) {instance =  new Singleton(); } return instance; }}Copy the code

This mode thread is uneasy to go

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

This mode is thread-safe but thread synchronization every time an instance is acquired is inefficient

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

Double checking ensures thread safety

There are three steps

1. Allocate memory space

2. Execute the constructor to initialize the object

3. Point the object to the space

The default value of the above step is 123. However, if 132 occurs and thread A is occupied, if thread B is also used at this time, the singleton will be considered as not empty and will be returned. However, the singleton has not been created yet. This is a void that leads to mistakes. Therefore, volatile is required before singleton.

Private static volatile Singleton; private static volatile Singleton; Private static final Singleton INSTANCE = new Singleton(); private static final Singleton INSTANCE = new Singleton(); } public static synchronized Singleton getInstance() { return SingletonIntstance.INSTANCE; }}Copy the code
Public class SingletonTest07 {} // enumeration enum Singleton {INSTANCE; }Copy the code