Thread-safe singleton example .NET optimized, The singleton pattern ensures a class has only one instance and provides a global point of access to it.
Namespace:
CA.Examples.Patterns.GOF.Singleton.PatternAssembly: CA.Examples (in CA.Examples.dll) Version: 1.0.0.0 (1.0.0.0)
Remarks
The singleton pattern implemented in .NET simply uses a private constructor and a static readonly instance variable that is lazily initialized. This ensures there is only one instance of the class.
Thread safety is guaranteed by the compiler. The Class is then sealed to prevent overriding behavior.
The only method of accessing the class is through the Instance method as such provides the single global point of access
CopyC#
source code:
//Source code from the Code Associate C# code library, Full documentation and latest updates can be found //@ http://www.codeassociate.com/caapi/ namespace CA.Examples.Patterns.GOF.Singleton.Pattern { public sealed class Singleton { // use a private constructor to prevent this class been created. To be a Singleton you need to guarantee the constructor cannot be called outside this class private Singleton() { } // using a lazily initialized static varaible thread safety is guaranteed by the compiler. private static readonly Singleton _instance = new Singleton(); public static Singleton Instance { get { return _instance; } } } }