The singleton pattern is divided into two kinds, the lazy type and the A hungry man type. The difference is the time to create the instance. A hungry man creates an instance when the class is loaded, and the lazy type is created when it needs to be acquired.
Package Create.f.singleton;public class Singleton {private Singleton () {}protected static Singleton getinstance () { System.out.println ("Get Singleton Singleton object"); return instance;} private static Singleton instance = new Singleton (); A hungry man type Note at this time thread safety}
Package create.f.singleton;//lazy public class Singleton2 {private static Singleton2 instance = Null;private Singleton2 () { }protected Static synchronized Singleton2 getinstance () {if (instance = = null) {SYSTEM.OUT.PRINTLN ("Initialize Singleton2 singleton") ; instance = new Singleton2 ();} return instance;}}
Package Create.f.singleton;public class Client {public static void main (string[] args) {Singleton Singleton = singleton.ge Tinstance (); Singleton s = singleton.getinstance (); System.out.println ("Whether the same object:" + (singleton = = s)); Singleton2 s2 = singleton2.getinstance (); Singleton2 s3 = Singleton2.getinstance (); Singleton2 S4 = Singleton2.getinstance (); System.out.println ("is the same object:" + (S2 = = S3 && S3 = = S4));}}
05. Create ———— Singleton mode