Wrote a lot of single-instance pattern implementation, today paste a book in the wording.
Singleton pattern Definition: A design pattern that is used when only one instance of a class is to be created.
Requirement: There can only be one way to create an instance, and you cannot get an object reference in an uninitialized state.
Therefore, in singleton mode, you need to have a construction method that is declared private and is called only once.
PackageOop/** * Single case Mode * * @author lunatictwo */ Public class Singleton { Private Final StaticSingleton instance =NewSingleton ();Private Static BooleanIsinit =false;//constructor method, only the constructor is called when initializing the instance Private Singleton() {Super(); }Private void Init() {//Initialize method is placed in private method}//Obtain an instance by static helper method Public Static synchronizedSingletongetinstance() {if(Isinit) {returnInstance//Determine if activation} instance.init ();//Activates the instance and saves the state as activated and does not initialize again the next time the request is createdIsinit =true;returnInstance }}
At this point, when obtaining a singleton instance, it can only be obtained by getinstance ().
How Java Singleton patterns are written