DEV Community

Juarez Júnior for Develop4Us

Posted on • Edited on

C# Design Pattern: Singleton

The Singleton pattern is useful when we need to ensure that a class has only one instance throughout the application. It’s like having a single controller for an important resource. This is handy for situations such as managing access to a log file, a database connection, or even system settings that need to be accessed from anywhere. The Singleton ensures that access is always through the same instance, avoiding duplication and wasted resources.

C# Code Example:

public class Singleton
{
    private static Singleton _instance;

    // Private constructor to prevent external instantiation
    private Singleton() { }

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

    public void ShowMessage()
    {
        Console.WriteLine("Singleton instance active!");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Singleton s1 = Singleton.Instance;
        Singleton s2 = Singleton.Instance;

        s1.ShowMessage();

        // Check if both instances are the same
        Console.WriteLine(s1 == s2);  // True
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

In the code, the Singleton class ensures that only one instance exists. The constructor is private, meaning no one can create another instance directly. The Instance method returns this single instance, creating it only if it doesn’t already exist. In the main program, both s1 and s2 refer to the same instance, confirmed by the comparison s1 == s2.

Conclusion:

The Singleton is a simple and effective pattern to ensure a class has only one instance, especially useful in situations where you want to avoid unnecessary duplication, like in connections or settings. It’s important to use it carefully to avoid dependencies that can make maintenance and testing harder.

Source code: GitHub

Top comments (0)