Learn Programming

Singleton Design Pattern

What is a singleton?

A singleton is a type of class that ensures that only one instance of the class is instantiated and at the same time makes it available globally to any other part of the program. It is also used to make sure that the class is instantiated only when it is needed.

What is it used for?

You can use a singleton for something like a database connection since you often only want one connection to a database. You could also use a singleton for a class that stores global settings for you program. There are many other ways to use it.

How to create a singleton

First create a normal class. We will called it Singleton.

using System;

class Singleton
{
}

Next you must create a class level variable of the same type as the current class for storing the instance of the class. This variable must be static.

using System;

class Singleton
{
    private static Singleton _Instance;
}

Now we will add the constructor which must be private because we don't want any other part of the program to be able to instantiate the class.

using System;

class Singleton
{
    private static Singleton _Instance;

    private Singleton()
    {
    }
}

We now need a method to access the instance of the class. This method must be static so that it can be run without instantiating the class. It is most often called GetInstance(). What it does is check whether an instance of the class exists and if it doesn't then it instantiates it and returns the instance.

using System;

class Singleton
{
    private static Singleton _Instance;

    private Singleton()
    {
    }

    public static Singleton GetInstance()
    {
        if (_Instance == null)
            _Instance = new Singleton();
        return _Instance;
    }
}

You will then need to add the methods that you need to the class. As an example I will add a method called PrintHello() that simply prints "Hello".

using System;

class Singleton
{
    private static Singleton _Instance;

    private Singleton()
    {
    }

    public static Singleton GetInstance()
    {
        if (_Instance == null)
            _Instance = new Singleton();
        return _Instance;
    }

    public void PrintHello()
    {
        Console.WriteLine("Hello");
    }
}

Here is a test program that shows how to use the singleton class.

using System;

class Program
{
    static void Main(string[] args)
    {
        Singleton s = Singleton.GetInstance();
        s.PrintHello();
        Console.ReadLine();
    }
}