A. Features:
① Singleton class can have only one instance
② Singleton classes must create their own unique instances themselves
③ Singleton class must provide this instance to all other objects
Two. Implementation method:
① a hungry man type
public class singleton1{Private Singleton1 (); private static Singleton1 single=new Singleton1 (); public static final Singleton1 getinstance () {return single; } }
② Lazy 1 (thread insecure)
public class singleton1{Private Singleton1 (); private static Singleton1 Single=null; public static Singleton1 getinstance () {if (single==null) {single=new Singleton1 (); } return single; } }
This approach is because no lock is added to the GetInstance method, and it produces multiple Singleton1 instances when multiple threads are accessing the method at the same time.
③ Lazy 2 (thread-safe, but inefficient, that is, adding a thread lock [the place where the lock is a waste of time, if you can reduce the determination of the lock can save time])
public class singleton1{Private Singleton1 (); private static Singleton1 Single=null; public static synchronized Singleton1 getinstance () {if (single==null) {single=new Singleton1 (); } return single; } }
④ Lazy 3 (thread-safe, high-efficiency, double-judge)
public class singleton1{ private singleton1 (); private static singleton1 single=null; public static singleton1 getinstance () { if (single==null) { synchronized (Singleton1.class) { if (Single==null) { s=new singleton1 (); } } } return single; } }
About singleton patterns in Java