Five-minute single sample mode with one Design Pattern
Five minutes a design pattern, the simplest way to describe the design pattern.
Understanding Singleton Mode
The Singleton mode is a simple design mode. It defines that a class has only one instance and provides a global access point to it.
Some database operation classes or tool classes use the singleton mode.
Sample Code
Public class Singleton {// declare the constructor as private to prevent external users from directly creating objects through the constructor. Only private Singleton () {} private static Singleton uniqueInstance can be created within the class; public static Singleton GetInstance () {lock (uniqueInstance) {// when an object needs to be created, call a private constructor to create the object // the object is not null in the next call, the object instance is directly returned. // Therefore, the uniqueInstance value is instantiated once, And the // Singleton class only has such an object if (uniqueInstance = null) uniqueInstance = new Singleton (); return uniqueInstance ;}} public void DoSomething () {Console. writeLine ("do something with unique instance ");}}
External programs can pass anywhere and can only pass throughSingleton.GetInstance()
To obtain the Singleton object instance.
This class is described in C. The above Code does not directly instantiate the uniqueInstance object, but instantiates the uniqueInstance object only when the GetInstance method is called. This method becomes a lazy implementation. Lock (uniqueInstance) is used to achieve mutually exclusive access between threads, and is considered for thread security.
There is also a way to implement the hungry Chinese style. This method is simpler and thread security is not required.
Public class Singleton {// declare the constructor as private to prevent external users from directly creating objects through the constructor. The object private Singleton () can only be created within the class () {} private static Singleton uniqueInstance = new Singleton (); public static Singleton GetInstance () {return uniqueInstance;} public void DoSomething () {Console. writeLine ("do something with unique instance ");}}