Singleton

A singleton is a design pattern that is used to ensure that a class has only one instance, and provides a global point of access to it.

Here’s an example of how you might implement a singleton 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 example, the Singleton class has a private constructor, which prevents other classes from creating instances of it. It also has a public static property called Instance, which returns the single instance of the class. The instance is created the first time the Instance property is accessed, and it is cached for subsequent accesses.

Here’s an example of how you might use the singleton. This code will output “The instances are the same.”, because both s1 and s2 refer to the same instance of the Singleton class.

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

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