Singleton Design Pattern

The Singleton design pattern is a creational pattern “that ensures a class has only one instance, while providing a global access point to this instance”. This can be useful when exactly one object is needed to coordinate actions across the system.

In C#, you can implement the Singleton pattern in various ways, but the most common approaches are through lazy initialization and thread safety considerations. We will discuss that in a while, lets first see how it works basically with examples.

Structure

The Singleton class declares the static method getInstance that returns the same instance of its own class. The Singleton’s constructor should be hidden from the client code. Calling the getInstance method should be the only way of getting the Singleton object.

Singleton implementation

using System;
public class Singleton
{
    private static Singleton _instance;

    // Private constructor ensures that the class cannot be instantiated from outside.
    private Singleton() 
    { 
    }

    // Public property to get the single instance of the class.
    public static Singleton Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new Singleton();
            }
            return _instance;
        }
    }

    // Example method to demonstrate functionality
    public void ShowMessage()
    {
        Console.WriteLine("Hello from Singleton!");
    }
}
static void Main(string[] args)
{
	Singleton singleton = Singleton.Instance;
	singleton.ShowMessage();
}

In this example:
  • The Singleton class has a private static field _instance that holds the single instance of the class.

  • The constructor is private to prevent external instantiation.

  • The Instance property provides a global access point to the instance. It initializes _instance only if it is null, ensuring only one instance is created.

How to implement a Thread-Safe Singleton Design Pattern in C#?

Ways to Implement the Thread-Safe Singleton Design Pattern in C#:

  1. Thread Safe Singleton using Lock

  2. Thread Safe Singleton using Eager Loading

  3. Thread Safe Singleton using Lazy Loading

We will discuss all the above concepts to Implement the Thread-Safe Singleton Design Pattern in C# in upcoming topics.

Summary

Singleton design pattern guarantees that only one instance of the class will be available throughout the application which ensures that you do not waste memory for a new object instance when you don’t need one.

In layman terms - The government is an excellent example of the Singleton pattern.
A country can have only one official government. Regardless of the personal identities of the individuals who form governments, the title, “The Government of CountryA”, is a global point of access that identifies the group of people in charge.