Showing posts with label Singleton pattern. Show all posts
Showing posts with label Singleton pattern. Show all posts

Thursday, 2 March 2023

Singleton pattern with example

The Singleton pattern is used to ensure that only one instance of a class is created throughout the lifetime of the application. This is useful when you want to control access to a shared resource, such as a database connection, or when you want to limit the number of instances of a class to one.

Here's an example implementation of the Singleton pattern in C#:

public class Singleton
{
    private static Singleton instance;

    private Singleton() { }

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

In this implementation, the class Singleton has a private constructor to prevent external instantiation, and a private static field instance that holds the single instance of the class. The Instance property is a public static property that returns the single instance of the class. The property first checks if the instance field is null, and if so, it creates a new instance of the Singleton class.

To use the Singleton, you can simply call the Instance property on the class, like this:


Singleton s1 = Singleton.Instance;
Singleton s2 = Singleton.Instance;

if (s1 == s2)
{
    Console.WriteLine("s1 and s2 are the same instance.");
}


In this example, s1 and s2 are both instances of the Singleton class, but because the class is implemented as a Singleton, they both refer to the same instance. The output of the above code will be "s1 and s2 are the same instance.".

Note that in multi-threaded environments, additional measures must be taken to ensure thread-safety when implementing the Singleton pattern.