Singleton Pattern C#

Singleton Pattern is one the most popular patterns in programming. Singleton is a class which only allows a single instance of itself to be created. It can be very useful, for example when Class contains List of object we don’t want to create new list each time we call the class, and we also want to keep the list private to restrict access and avoid possible corruption. Singleton usually gives simple access to that instance. There are several ways of implementing the pattern, in multi-threading application we must consider case where constructor is called from two thread at the same time, to fix this problem we need to implement thread safety version. Let start with simplest, not thread safe, implementation.

public class Singleton
{
  private static Singleton instance;

  private Singleton() { }

  public static Singleton Instance
  {
    get
    {
       if (instance == null)
       {
          instance = new Singleton();
       }
       return instance;
    }
  }

This Singleton class contains private static Singleton Class instance. Those keywords are very important, Private makes the instance accessible only from current class( Instance getter)  what prevents other classes from accessing it in not safe way. Static makes it shared across all instances. You can find more about statics, here.

Constructor of this class( Singleton() ) is private, and its called from Instance getter, if its not created yet.

Instance property is read only and it returns the instance of the class, always the same instance for all calls. If you don’t know how get{} works, check my post about it  here.

Here is thread safety version of this Pattern, It prevents from creating two instances when getter is called from multiple threads.

First we need to add object that will be responsible for handling multiple thread access.


private static readonly object padlock = new object();

New we need to add one condition to Instance parameter that will lock the firs thread that is accessing it.

public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
}

 

All these implementations share four common characteristics, however:
  • A single constructor, which is private and parameterless.
  • A static variable which holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating one if necessary.
 

In next post You will see real word examples of using this patter. One day I’ll demonstrate how to use it In Unity to create MusicManager, that is playing music between game scenes. Singleton have many uses and It’s one of the simplest patterns to learn. In next articles I’ll try to describe all most popular design patterns. Stay Awesome!