Usage scenarios:
In software development, software developers want some service classes and only one instance for other programs to use. Such as: the printer service program or some control of the system environment, in order to avoid inconsistencies caused by temples access, want to provide only one instance for other programs, as well as the environment to generate a unique sequence number or create an object need to consume too much resources (to access resources such as IO and database).
A global variable can be used for an object that is used by the entire system, and a unique instance can be guaranteed if the program is written correctly, but there is no guarantee that there is only one instance of the system if the system expands with it.
A class diagram of a singleton pattern:
Singleton mode is a relatively simple design pattern, which essentially instantiates itself and always provides a unique instance of a class to the system.
A singleton pattern implementation code:
Lazy mode:
public class singleton{ static Singleton singleton= private Singleton () {} public static Singleton Getsingleton () { if (Singleton =null ) {Singleton = new Singleton ();} return Singleton;}}
This mode is thread insecure in multi-threaded concurrency mode, all in case of high concurrency problems, you can add the Synchronized keyword before the Getsingleton method, of course, you can also add synchronized keyword within the Getsingleton method, This is for Java, and if you use. NET, lock locks are used to achieve thread safety.
A Hungry man mode:
Public class singleton{privatestaticfinal Singleton singleton=new Singleton () ; Private Singleton () {} Public Static Singleton Getsingleton () {return Singleton;}}
A singleton pattern of design patterns