Singleton Design Pattern in C# with Example

1. Definition

The Singleton pattern is a design pattern that ensures a class has only one instance and provides a global point of access to that instance. It is a way to provide a controlled access point to a single instance of a class.

2. Problem Statement

Imagine you have a configuration manager for your application. If multiple instances of this manager are created and each holds different states, it could lead to inconsistent application behavior.

3. Solution

The Singleton pattern restricts the instantiation of a class to just one object. This is useful when only one instance is required to control actions, such as in the case of a configuration manager or a logging class.

4. Real-World Use Cases

1. Database connection pools where you want to limit the number of connections.

2. Logging mechanisms to maintain a single log file.

3. Configuration managers for application-wide settings.

5. Implementation Steps

1. Make the constructor of the class private.

2. Create a private static instance of the class.

3. Provide a public static method to get the instance of the class.

6. Implementation in C#

// Singleton class
public sealed class Singleton
{
    // Static instance of the class
    private static Singleton _instance = null;

    // Lock object for thread-safety
    private static readonly object lockObject = new object();

    // Private constructor
    private Singleton()
    {
    }

    // Public method to get the instance
    public static Singleton Instance
    {
        get
        {
            lock (lockObject)
            {
                if (_instance == null)
                {
                    _instance = new Singleton();
                }
                return _instance;
            }
        }
    }

    public void DisplayMessage()
    {
        Console.WriteLine("Singleton instance invoked!");
    }
}

public class Program
{
    public static void Main()
    {
        // Get the Singleton instance and display a message
        Singleton singleton = Singleton.Instance;
        singleton.DisplayMessage();
    }
}

Output:

Singleton instance invoked!

Explanation:

In this example, the Singleton class has a private constructor, which ensures that no other class can create an instance. The static Instance property provides a single access point to the instance of the Singleton class. The lockObject ensures thread safety.

7. When to use?

Use the Singleton pattern when:

1. There must be exactly one instance of a class, which is accessible to clients from a well-known access point.

2. The single instance should be extendable by subclassing, and clients should be able to use an extended instance without modifying their code.

3. The instance is used across the application to maintain a particular state or provide utility functions.


Comments