1, a Hungry man type single case mode
A hungry man singleton mode-by Chimomonamespace csharplearning{public sealed class Singleton { private static readonly Sing Leton instance = new Singleton (); Private Singleton () {} public static Singleton Instance { get {return Instance;} } }
2, lazy single-case mode
2.1, the use of internal class
Lazy Singleton mode: With an internal class-by Chimomonamespace csharplearning{public sealed class Singleton { private Singleton () { } private Static class Singletonholder {public static readonly Singleton instance = new Singleton (); } Public static Singleton Instance { get {return singletonholder.instance;}}}
2.2, Ordinary Lock
Lazy single-case mode: normal lock-by chimomonamespace csharplearning{public sealed class Singleton { private static volatile Singleton instance; private static readonly Object syncRoot = new Object (); Private Singleton () {} public static Singleton Instance { get { lock (syncRoot) { if ( instance = = null) { instance = new Singleton ();} } return instance;}}}
2.3. Double Detection plus lock
Lazy single-case mode: Dual detection lock-by chimomonamespace csharplearning{public sealed class Singleton { private static volatile Singleton instance; private static readonly Object syncRoot = new Object (); Private Singleton () {} public static Singleton Instance { get { if (Instance = = null) { Lock (SyncRoot) { if (instance = = null) { instance = new Singleton (); }}} return instance;}}}
Design Patterns-thread-safe Singleton mode (C #)