A single case pattern
The singleton pattern (Singleton pattern) provides a great way to create objects. This pattern involves a single class that is responsible for creating its own objects, while ensuring that only a single object is created. This class provides a way to access its only object, which can be accessed directly without instantiating an object of that class.
Primary solution: A globally used class is frequently created and destroyed.
Key code: The constructor is private.
Usage scenarios:
Windows is multi-threaded, in the operation of a file, it is inevitable that multiple processes or threads simultaneously manipulate a file, so all files must be processed through a unique instance.
Class Diagram:
Two implementation codes
A Singleobject class is created. The Singleobject class has its own private constructor and a static instance of itself. The Singleobject class provides a static method for the outside world to obtain a static instance of it.
1 Creating a Singleton class
Singleobject.java
Public classSingleobject {//create an object of Singleobject Private StaticSingleobject instance =NewSingleobject (); //let the constructor be private so that the class is not instantiated PrivateSingleobject () {}//get the only available objects Public StaticSingleobject getinstance () {returninstance; } Public voidShowMessage () {System. out. println ("Hello world!, address is:"+ This); }}
2. Run the test case
Singletonpatterndemo.java
Public classSingletonpatterndemo { Public Static voidMain (string[] args) {//Illegal Constructors//compile-time error: Constructor Singleobject () is not visible//Singleobject object = new Singleobject (); //get the only available objectsSingleobjectObject=singleobject.getinstance (); //displaying Messages Object. ShowMessage (); }}
In the actual development of the main use of double check lock/double check lock (DCL, that is, double-checked locking) way to achieve a single case mode
JDK version: JDK1.5 up
Whether Lazy initialization: Yes
Whether multithreading security: Yes
Difficult to achieve: more complex
Description: This approach uses a dual-lock mechanism to maintain high performance in a secure and multi-threaded environment.
The performance of getinstance () is critical to the application.
code example:
Public classSingleton {Private volatile StaticSingleton Singleton; PrivateSingleton () {} Public StaticSingleton Getsingleton () {if(Singleton = =NULL) {synchronized (Singleton.class) { if(Singleton = =NULL) {Singleton=NewSingleton (); } } } returnSingleton; } }
Next design mode-07 Adapter mode (structured mode)
Design mode-06 Singleton mode (Create mode)