The Singleton mode requires that a class has only one instance and provides a global access point.
1. Single-threaded Method
Public sealed class singlton {static singlton instance = NULL; singlton () {} public static singlton instance {get {If (instance = NULL) {return New singlton ();} return instance ;}}}
This if (instance = NULL) statement is not thread-safe and may generate multiple instances.
2. Thread-safe
Public sealed class singlton {static singlton instance = NULL; static readonly object o = new object (); singlton () {} public static singlton instance {get {lock (o) {If (instance = NULL) {return New singlton () ;}return instance ;}}}}
The object instance is created by the first thread to enter. The later thread (instence = NULL) is false and will not be created again. However, this implementation method adds additional overhead and reduces performance.
3. Double Lock
Public sealed class singlton {static singlton instance = NULL; static readonly object o = new object (); singlton () {} public static singlton instance {get {If (instance = NULL) {lock (o) {If (instance = NULL) {return New singlton () ;}} return instance ;}}}
AvoidInstanceAn exclusive lock exists in all calls to the property method.
4.Static Initialization
Public sealed class singlton {static readonly singlton instance = new singlton (); static singlton () {} public static singlton instance {get {return instance ;}}}
5. Delayed static Initialization
Public sealed class singlton {static singlton () {} public static singlton instance {get {return createsinglton. instance ;}} class createsinglton {internal static readonly singlton instance = new singlton (); static createsinglton (){}}}