Design Mode: Three creation modes of Singleton mode and their respective advantages and disadvantages
Singleton mode: ensures that a class has only one instance and provides global access points. The implementation of Singleton mode in Java requires a private constructor, a static method, and a static variable. Determine the performance and resource restrictions, and how to select an appropriate solution to implement Singleton to solve the problem of multithreading. If multiple class loaders are used, a single instance may become invalid and multiple instances may be generated. The double check lock does not apply to java 1.4 or earlier versions.
Method 1:
Package singleton;/*** synchronous getInstance () method: * a bit: Ensure thread security. * Disadvantage: the performance is greatly reduced * @ author Arvon **/public class Singleton1 {private static Singleton1 instance; private Singleton1 () {} public static synchronized Singleton1 getInstance () {if (instance = null) instance = new Singleton1 (); return instance ;}}
Method 2:
Package singleton;/*** "eager" to create an instance * advantages: thread security * disadvantages: increase the burden of Program Creation and running * @ author Arvon **/public class Singleton2 {private static Singleton2 instance = new Singleton2 (); private Singleton2 () {} public static Singleton2 getInstance () {return instance ;}}
Method 3:
Package singleton;/*** double check lock * @ author Administrator **/public class Singleton3 {private volatile static Singleton3 instance; private Singleton3 () {} public static Singleton3 getInstance () {if (instance = null) synchronized (Singleton3.class) {// only enters the synchronization block for the first time if (instance = null) instance = new Singleton3 ();} return instance ;}}