define

Ensure that a class has only one instance and provide a global access point to access it.

Take the instance creation back, let the class create the instance itself, and then let the class provide external access to the method of the class instance.

nature

Control the number of instances

His role

  • Singleton

    Responsible for creating a unique instance of the Singleton class itself, and providing a getSingleton method to allow external access to the unique instance.

The implementation of singleton pattern

The hungry type
Public class Singleton1 {private Singleton1(){} public static Singleton1 = private Singleton1(){} public static Singleton1 = private Singleton1(){} Public static Singleton1 = private Singleton1(){} Public static Singleton1 = private Singleton1(){ new Singleton1(); public static Singleton1 getInstance(){ return singleton1; }}Copy the code
LanHanShi
/** * lazy * create expensive, so delayed instantiation, Public class Singleton2 {private Singleton2(){} private static Singleton2 Singleton2; // Double check mode, the drawback is that due to the JVM instructions reorder, Public static Singleton2 getInstance(){if(Singleton2 == null){synchronized (singleton2.class){public static Singleton2 getInstance(){if(Singleton2 == null){synchronized (singleton2.class){ if(singleton2 == null){ singleton2 = new Singleton2(); } } } return singleton2; }}Copy the code
Static inner class
*/ public class Singleton3 {private Singleton3(){} private static class Singleton3Handler{private static Singleton3 singleton3 = new Singleton3(); } public static Singleton3 getInstance(){ return Singleton3Handler.singleton3; }}Copy the code
The enumeration
/** * enumeration */ public enum Singleton4 {SINGLETON_4; public static Singleton4 getInstance(){ return SINGLETON_4; }}Copy the code

function

Used to ensure that a class has only one instance at runtime and provides a global access point. You only care about class creation.

When to use

When only one instance of a class needs to be controlled.