Singleton principle:

  • Construct private.

  • There can only be one instance of a singleton class (especially for thread safety in multithreaded situations)

  • Return instances as static methods or enumerations.

  • Ensure that objects are not rebuilt when the antisequence is changed

The hungry mode

// The hunchman singleton class. When the class is initialized, Public class Singleton {private Singleton() {} private static final Singleton INSTANCE = new Singleton(); Public static Singleton getInstance() {return INSTANCE; }}Copy the code

In hungry mode, a static object is created at the same time the class is created, so there is no thread-safety problem.

Lazy mode

// lazy singleton class. Public class Singleton {private Singleton() {} private static Singleton INSTANCE =null; Public static Singleton getInstance() {if (single == null) {INSTANCE = new Singleton(); } return INSTANCE; }}Copy the code

Lazy mode synchronizes thread-safe methods

1 Double check lock

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

Static inner class

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

Enumerate singleton definitions

Since Java version 1.5, single-element enumerations have been the best way to implement the singleton pattern.

public enum EnumSingleton { INSTANCE; public EnumSingleton getInstance(){ return INSTANCE; }}Copy the code