Java Design pattern Single-instance mode (seven notation)
The first, lazy, lazy initialization, thread insecure, multi-threading does not work:
Public class Singleton { privatestatic Singleton instance; Private Singleton () {}// privatisation constructor method to prevent class from being instantiated public static Singleton GetInstance () { ifnull) { new Singleton (); } return instance;} }
The second type, lazy, lazy initialization, thread-safe:
- Advantage: The first call is initialized to avoid memory waste.
- Disadvantage: You must lock synchronized to guarantee a single case, but locking will affect efficiency.
public class Singleton { private static Singleton instance; private Singleton () {} public static Synchronized Singleton getinstance () { if< /span> (Instance = = null ) {instance = new Singleton (); return instance; } }
The third type, a hungry man, is not lazy initialization, thread safety:
- Advantages: Without locking, execution efficiency will increase.
- Disadvantage: The class loads when it initializes, wasting memory.
Public class Singleton { privatestaticnew Singleton (); Private Singleton () {} Public Static Singleton getinstance () { return instance; }
Fourth type, a hungry man, lazy initialization, thread safety:
public class Singleton { private Singleton instance = Span style= "COLOR: #0000ff" >null ; static {instance = new Singleton (); private Singleton () {} public static Singleton getinstance () { return this.instance; } }
Fifth type, static inner class, lazy initialization, thread safety:
The third difference is that the Singleton class is loaded, and the instance is not necessarily initialized. Because the Singletonholder class is not actively used, the Singletonholder class is explicitly loaded only by explicitly invoking the GetInstance method, thereby instantiating the instance.
Public classSingleton {Private Static classSingletonholder {Private Static FinalSingleton INSTANCE =NewSingleton (); } PrivateSingleton () {} Public Static FinalSingleton getinstance () {returnsingletonholder.instance; } } The sixth type (enumeration), not lazy initialization, is thread safe:
Public enum Singleton { INSTANCE; Public void Whatevermethod () { }
Seventh type, double check lock DCL (double-checked locking), lazy initialization, thread safety:
JDK1.5, using a dual-lock mechanism, safe and in multi-threaded situations to maintain high performance.
Public classSingleton {Private volatile StaticSingleton Singleton; PrivateSingleton () {} Public StaticSingleton Getsingleton () {if(Singleton = =NULL) { synchronized(Singleton.class) { if(Singleton = =NULL) {Singleton=NewSingleton (); } } } returnSingleton; } }
Java Design pattern Single-instance mode (seven notation)