How to use Singleton design pattern in C#

By FoxLearn 2/16/2024 8:35:53 AM   87
This post shows you how to use Singleton design pattern in C#

Singleton is used to make sure only one object of the class is created.

Regular useVery high

UML Diagram

how to use singleton design pattern in c#

Classes and objects that participate in this pattern include: Singleton

Defining a method so that the client can only access one instance of the created class.

Responsible for creating and maintaining a unique object.

class SingletonPattern
{
    static void Main()
    {
        Singleton o1 = Singleton.Instance();
        Singleton o2 = Singleton.Instance();
        if (o1 == o2)
            Console.WriteLine("Objects are the same instance");
        Console.ReadKey();
    }
}

class Singleton
{
    private static Singleton _instance;

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

Singleton pattern is a widely used model, useful in many projects, so consider using, this is a very good pattern because it only creates one instance for a class.