The singleton pattern is that the so-called class can have only one instance, that is, the class can only be in an internal instance once, and then provide this instance, and the external cannot instantiate the class.
The characteristics of the singleton mode:
1, there can only be one instance;
2, can only create their own unique instance;
3. This instance must be provided to all other objects.
Normal singleton mode (no thread safety is considered)
// <summary> ///single-case mode/// </summary> Public classSingleton {Private StaticSingleton Singleton; PrivateSingleton () {}/// <summary> ///get instance-thread non-secure mode/// </summary> /// <returns></returns> Public StaticSingleton Getsingleton () {if(Singleton = =NULL) Singleton=NewSingleton (); returnSingleton; } }
Consider multithreading security
/// <summary> ///single-case mode/// </summary> Public classSingleton {Private Static Objectobj =New Object(); Private StaticSingleton Singleton; PrivateSingleton () {}/// <summary> ///Get instance-thread safety/// </summary> /// <returns></returns> Public StaticSingleton Getthreadsafesingleton () {if(Singleton = =NULL) { Lock(obj) {singleton=NewSingleton (); } } returnSingleton; } }
C # Design pattern (1)--Singleton mode (Singleton)