The singleton pattern ensures that there is only one instance of a class, and that it instantiates itself and provides this instance to the entire system, which has the following characteristics:
1, the Singleton class can have only one instance.
2. The Singleton class must create its own unique instance itself.
3. The Singleton class must provide this instance to all other objects.
The singleton mode is divided into lazy mode and a hungry man mode:
Lazy mode is instantiated at the first invocation of the program. is not thread-safe. However, you can make it safe by rewriting the method.
The A Hungry man mode begins to instantiate at load time, ensuring that an instance already exists at the time of invocation. is thread-safe, but the memory overhead seems a bit large.
Lazy-style Sample code:
1 Public classSingleton {2 //privatization default constructor3 PrivateSingleton () {}4 Private StaticSingleton single=NULL; 5 //Static Factory Method6 Public StaticSingleton getinstance () {7 if(single =NULL) { 8Single =NewSingleton (); 9 } Ten returnSingle ; One } A}
A Hungry Man sample code:
1 Public classSingleton {2 PrivateSingleton () {}3 Private Static FinalSingleton single =NewSingleton (); 4 Public StaticSingleton getinstance () {5 returnSingle ; 6 } 7}
Lazy Thread-safety improvements, Method 1:
1 Public classSingleton {2 //privatization default constructor3 PrivateSingleton () {}4 Private StaticSingleton single=NULL; 5 //static Factory method (plus synchronous method)6 Public StaticSingleton Synchronized getinstance () {7 if(single =NULL) { 8Single =NewSingleton (); 9 } Ten returnSingle ; One } A}
Method 2:
1 Public classSingleton2 { 3 //Privatization constructor4 PrivateSingleton () {}5 //static inner class6 Private Static classSingletonholedr () {7 Private Static FinalSingleton instance =NewSingleton (); 8 } 9 //Static Factory methodTen Public Static FinalSingleton getinstance () { One returnsingletonholedr.instance; A } -}
Generally I am more fond of using method 2. There are still a lot of things not involved in the singleton model. This is my study note, if quoted please be cautious.
And if any man finds himself in the wrong trouble, help leave a message to correct it.
Single-instance design pattern for Java design Patterns