The Java singleton pattern implements the attribute of only one instance of a class.
Implementation mode: A hungry man type is very simple not elaborated. Below is a description of the lazy type.
- Constructor privatization
- The static method obtains the instance, the method inside double-check-locking checks. Synchronization methods are not recommended.
public class Singleton { private static Singleton Singleton; Private Singleton () {} public static Singleton getinstance () { if (Singleton = = null) {// try {// Thread.Sleep (+),// } catch (Interruptedexception e) {// e.printstacktrace ();/ } synchronized (singleton.class) { if (Singleton = = null) { Singleton = new Singleton ();}} } return singleton;} }
The code above is intended to make the single-mode failure more likely when there are no synchronized blocks and two checks. The test code will not be written.
Java Singleton mode