The singleton mode means that there can be only one object in the system for a class, and it is impossible to come up with a second one.
1. Singleton mode - a Hungry man (thread-safe, no synchronization mechanism required)
public class Singleton {private static Singleton instance=new Singleton (); Initializes an instance object directly to the private Singleton () { ///private type constructor to ensure that other class objects cannot be directly new to an instance of the object} public static Singleton GetInstance () { //The only public method of this class is return instance; }}
One drawback of the above code is that when the class is loaded, it is directly new to a static object, and when there are more such classes in the system, the startup speed slows down. Now the popular design is to say "lazy loading", we can initialize the first class object at the first use.
2. Singleton mode - lazy (thread insecure, using synchronous method )
public class Singleton { private static Singleton instance;
Private Singleton () {
} synchronized Singleton getinstance () { //Synchronize the method that gets the instance if (instance = = null) instance = new Singleton (); return instance; }
}
One of the above code locks a method, the granularity is a bit large, the improvement is only locked in the new statement is OK.
3. Singleton mode - lazy (thread insecure, use synchronous code block )
public class Singleton { private static Singleton instance; Private Singleton () { } public static Singleton getinstance () { //Synchronize the method that gets the instance if (instance = = null) { synchronized (singleton.class) { if (instance = = null) instance = new Singleton ();} } return instance; } }
Thread safety issues in Singleton mode