Design Pattern-Singleton pattern
The Singleton mode is a simple mode in the design mode, and also a mode that is used more often.
Especially when only one object is needed, such as the thread pool, cache, log object, and registry object.
If multiple instances are created, many problems may occur. Such as abnormal program behavior and excessive resource usage.
The Singleton mode ensures that a class in the program has only one instance at most.
The Singleton mode provides global points for accessing this instance.
In JAVA, the singleton mode requires: private constructor, a static method, and a static variable.
If multiple class loaders are used, the single instance may become invalid and multiple instances will be generated.
Singleton mode ensures that a class has only one instance and provides a global access point.
The following is the singleton mode of delayed loading:
public class Singleton {private static Singleton uniqueInstance;private Singleton() {}public static Singleton getInstance() {if (uniqueInstance == null) {uniqueInstance = new Singleton();}return uniqueInstance;}}
Multi-thread processing: You need to change getInstance () to Synchronized to easily solve the multi-thread problem.
public class Singleton {private static Singleton uniqueInstance;private Singleton() {}public static synchronized Singleton getInstance() {if (uniqueInstance == null) {uniqueInstance = new Singleton();}return uniqueInstance;}}
If the application always creates and uses the singleton mode, or the load is not heavy during creation and running, you may be eager to create an instance:
public class Singleton {private static Singleton uniqueInstance = new Singleton();private Singleton() {}public static synchronized Singleton getInstance() {return uniqueInstance;}}
Use "double check lock" to reduce the use of synchronization in getInstance:
/*** The volatile keyword ensures that when the uniqueInstance variable is initialized * To a Singleton instance, multiple Threads correctly process the uniqueInstance variable **/public class Singleton {private volatile static Singleton uniqueInstance = new Singleton (); private Singleton () {} public static Singleton getInstance () {/** check the instance. if the instance does not exist, enter the synchronization zone **/if (uniqueInstance = null) {/** the following code is thoroughly executed only for the first time **/synchronized (Singleton. class) {/** enter the block and check again. if it is still null, create an instance **/if (uniqueInstance = null) {uniqueInstance = new Singleton () ;}} return uniqueInstance ;}}