Java Singleton Mode
I have written many Singleton implementations, And I am posting a book today.
Singleton mode is defined as a design mode, which is used when you only need to create an instance for the class.
Requirement: You can only create an instance in one way, and cannot get an object reference in the uninitialized state.
Therefore, in singleton mode, a constructor declared as private must be called only once.
Package oop;/*** Singleton mode ** @ author lunatictwo */public class Singleton {private final static Singleton instance = new Singleton (); private static boolean isInit = false; // constructor. The constructor private Singleton () {super ();} private void init () is called only when the instance is initialized () {// put the initialization method in the private method} // obtain the public static synchronized Singleton getInstance () {if (isInit) {return instance through the static auxiliary method; // determine whether the instance is activated} instance. init (); // activate the instance and save the status as activated. isInit = true; return instance;} will not be initialized again the next time the instance is created ;}}
In this case, you can only get the instance by getInstance.