The Singleton mode ensures that only one instance of a class exists in a Java application.
Benefits:
Compared with global variables, it optimizes the system performance better, because it is used and instantiated.
Generally, Singleton mode has two forms:
The first form: it is also a common form.
Public class Singleton {Private Static Singleton instance = NULL; private Singleton () {// do something} // This method is better than the following method, so you do not need to generate objects every time, the instance is generated for the first time, improving the efficiency of public static Singleton getinstance () {If (instance = NULL) {instance = new Singleton () ;}return instance ;}}
Second form:
Public class Singleton {// define one of your own instances internally, for internal calls only Private Static Singleton instance = new Singleton (); Private Singleton () {// do something} // here is a static method for external access to this class. You can directly access public static Singleton getinstance () {return instance ;}}
PS: create a single piece in the static initializing device. This Code ensures thread security.
For multi-threaded access, we generally adopt the second "eager" approach, instead of the first latency processing method, this will solve the problem of sequential execution errors caused by multiple threads on a single access point.
Another method is to use double check shackles to reduce the use of synchronization in getinstance ().
public class Singleton{ private volatile static Singleton instance; private Singleton(){} public static Singleton getInstance(){ if(instance==null){ synchronized(Singletion.class){ if(instance == null){ instance = new Singleton(); } } } return instance; }}
The volatile keyword ensures that when the instance variable is initialized to a singletion instance, multiple threads correctly process the instance variable because it forces the variable to correspond to the shared variable in the memory.