Singleton Pattern

Singleton pattern is a simple design pattern in software practice and sometimes considered as an anti-pattern due its tight coupling nature.

A very simple non thread safe implementation of the Singleton pattern would be like this.

Singleton non thread safe

class Singleton
{
  privatestatic Singleton _instance;
  private Singleton()
  {
    Console.WriteLine(Singleton instantiated);
  }
 
publicstatic Singleton SingletonInstance
{
  get
   {
        if (_instance ==null)
            {
               // delay the object creation to demonstrate the thread saftey.
               Thread.Sleep(1500);
            _instance =new Singleton();
            }
      return     _instance;
  }
 }
}

Run the above class using Main method shown below, you can notice Singleton constructor is called twice by the both threads, since it is not thread safe. ( You can use the same Main methid implementation for all 3 Singleton implementations)

Main method implementation

class Program
{
staticvoid Main(string[] args)
{
new Thread(() => { Singleton sin1 = Singleton.SingletonInstance; }).Start();
Singleton sin2 = Singleton.SingletonInstance;
 
Console.ReadKey();
}
}

Singleton thread safe

Making the above implementation to a thread safe code is not a complex task, we can use our same old locking technique.

class Singleton
{
privatestatic Singleton _instance;
privatestaticobject _lock =newobject();
 
private Singleton()
{
Console.WriteLine(Singleton instantiated);
}
 
publicstatic Singleton SingletonInstance
{
get
{
lock (_lock)
{
if (_instance ==null)
  {
      // delay the object creation to demonstrate the thread saftey.
        Thread.Sleep(1500);
         _instance =new Singleton();
   }
return _instance;
}
}
}
}

The above is a perfect Singleton implementation in C#. But is there any other way that we can have the Singleton behavior without compensating our performance into locking. Because locking is a performance drop for sure.

Singleton C# way  – The trendy way

This is a neat and a trendy way to implement the Singleton.

We do not use locks in this implementation and it is very fast yet purely thread safe.

class Singleton
{
    privatestaticreadonly Singleton _instance;
 
    static Singleton()
    {
             _instance =new Singleton();
     }
 
    private Singleton()
   {
       Console.WriteLine(Singleton instantiated);
    }
 
   public static Singleton SingletonInstance
  {
     get
    {
      return _instance;
     }
  }
}

The magic is, static constructor.

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

To remeber simply you can think that the static constructor is called when the class is loaded.

More about static constructors in this MSDN article.

Advertisements

One thought on “Singleton Pattern

Comments are closed.

Powered by WordPress.com.

Up ↑

%d bloggers like this: