The singleton design pattern is one of the most popular design patterns in the programming world. A singleton
is a class that allows only a single instance of itself to be created.
In the code below, when getObj()
is called for the first time, it creates a Singleton obj and returns the same obj after that. This example is not a thread-safe method; two threads running at the same time can create two objects for Singleton.
// This method is not thread-safe.public sealed class Singleton{private static Singleton obj=null;// private constructor.private Singleton(){}// public static method for creating a single instance.public static Singleton getObj{get{if (obj==null){obj = new Singleton();}return obj;}}}
Note that Singleton obj is created according to the requirement of the user. This is called lazy instantiation.
// This method is thread-safe.public sealed class Singleton{private static Singleton obj = null;// mutex lock used forthread-safety.private static readonly object mutex = new object();Singleton(){}public static Singleton getObj{get{lock (mutex){if (obj == null){obj = new Singleton();}return obj;}}}}
In the above code, a mutex lock is implemented for mutual-exclusion. Similarly, in the code below, a nested private class is implemented. This allows a single instance of Singleton when it is referenced for the first time in getObj()
method.
public sealed class Singleton{private Singleton(){}public static Singleton getObj{get{return Nested.obj;}}// private nested class.private class Nested{// Explicit static constructor to tell C# compiler// not to mark type as beforefieldinitstatic Nested(){}internal static readonly Singleton obj = new Singleton();}}
Free Resources