🎉 Hooray! After 3 years of work, I've finally released the ebook on design patterns! Check it out »

C#: Singleton

Singleton

Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides single point of access to it for any other code.

Singleton has almost the same pros and cons as global variables. Although they’re super-handy, they break modularity of your code.

You can just use a class, which depends on Singleton, in some other context. You’ll have to carry the Singleton class as well. Most of the time, this limitation comes up during the creation of unit tests.

Learn more about Singleton

Application of the pattern in C#

Complexity:

Popularity:

Usage examples: A lot of developers consider the Singleton pattern an antipattern. That’s why its usage is on the decline in C# code.

Identification: Singleton can be recognized by a static creational method, which returns same cached object.

Example: Conceptual Example

This example illustrates the structure of the Singleton design pattern. It focuses on answering these questions:

  • What classes does it consists of?
  • What roles do these classes play?
  • In what way the elements of the pattern are related?

Program.cs: Conceptual Example

using System;

namespace Singleton
{
    // The Singleton class defines the `getInstance` method that lets clients
    // access the unique singleton instance.
    class Singleton
    {
        private static Singleton _instance;

        private static object _lock = new object();

        private Singleton()
        { }

        // The static method that controls the access to the singleton instance.
        //
        // This implementation let you subclass the Singleton class while
        // keeping just one instance of each subclass around.
        public static Singleton getInstance()
        {
            lock (_lock)
            {
                return _instance ?? (_instance = new Singleton());
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // The client code.
            Singleton s1 = Singleton.getInstance();
            Singleton s2 = Singleton.getInstance();

            if (s1 == s2)
            {
                Console.WriteLine("Singleton works, both variables contain the same instance.");
            }
            else
            {
                Console.WriteLine("Singleton failed, variables contain different instances.");
            }
        }
    }
}

Output.txt: Output

Singleton works, both variables contain the same instance.