A singleton pattern is often used in the project, which summarizes
1-A Hungry man
Public class Singleton { // a hungry man type Private Singleton () { } privatestaticnew Singleton (); Public Static Singleton getinstance () { return Singleton; } }
2 Lazy Thread-safe
Public classSingleton {//Lazy Type PrivateSingleton () {}Private StaticSingleton Singleton =NULL; Public Static synchronizedSingleton getinstance () {if(singleton==NULL){ return NewSingleton (); } returnSingleton; }}
3 Two-Lieutenant, thread-safe.
Public classSingleton {//double check PrivateSingleton () {}Private Static volatileSingleton Singleton =NULL; Public StaticSingleton getinstance () {if(singleton==NULL){ synchronized(Singleton.class){ if(singleton==NULL) { return NewSingleton (); } } } returnSingleton; }}
4 static internal classes are nested class thread-safe
Public class Singleton { private Singleton () {} privatestaticclass instanceholder{ privatestaticnew Singleton (); } publicstatic Singleton getinstance () { return Instanceholder.singleton;} }
Synchronized will affect service performance, why it will affect, not too clear, later understand in the supplement. Static inner classes (nested classes) are better in comparison
Four ways to get a single case