Singleton mode What is a singleton mode?
A singleton guarantees that only one instance of an object JVM can be used , and a common singleton lazy-a hungry man-
What is lazy , is needed to instantiate , thread is unsafe.
What is a hungry man is that when the class file is loaded, it is initialized and inherently thread-safe.
One-Example Lazy code
class singletontest { public static void main (string[] args ) { Singleton SL1 = Singleton. Getsingleton (); Singleton SL2 = Singleton. Getsingleton (); System. out . println (sl1 = = sl2); } }
Public class Singleton { // when needed, will be instantiated private static Singleton Singleton; Private Singleton () { } synchronized public static Singleton Getsingleton () { if (singleton = = null) { singleton = new Singleton (); } return Singleton; } } |
Double Test lock
// Lazy Type Second writing efficiency high double test lock static public Singleton GetSingleton2 () {
if (singleton = = null) { // First Step inspection lock synchronized (Singleton. class ) { // Second Step inspection lock if (singleton = = null) { singleton = new Singleton (); }
} }
return Singleton; } |
A Hungry Man type code
class SingletonTest1 { public static void Main (string[] args >) { Singleton1 SL1 = Singleton1. Getsingleton (); Singleton1 SL2 = Singleton1. Getsingleton (); System. out . println ((sl1 = = sl2) +"-"); } } Public class Singleton1 { // when class file is loaded and initialized private static Singleton1 singleton = new Singleton1 (); Private Singleton1 () { } public static Singleton1 Getsingleton () { return Singleton; }
} |
zbb20180930 design mode-Singleton mode