Thursday, January 26, 2023

Singleton Pattern C#

 

The Singleton pattern is a creational design pattern that ensures that a class has only one instance and provides a global point of access to it. The singleton pattern is used when only a single instance of a class should exist in the entire application and this instance should be easily accessible.

Here are some key characteristics of a singleton class:

  • A singleton class has a private constructor to prevent other classes from instantiating it.
  • It has a static method that returns the singleton instance, creating it if it doesn't already exist.
  • It maintains a static reference to the singleton instance, which is returned by the static method.

An example of a singleton class in C#:

 

 

public sealed class Singleton
{
    private static Singleton _instance = null;
    private static readonly object _lock = new object();

    private Singleton() {}

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

In this example, the Instance property is used to get the singleton instance, and a private constructor and a private static variable ensure that the class can only be instantiated once. Singletons have some benefits such as providing a single point of access for a particular resource, or for maintaining global state, but it also has some drawbacks like hard to test, if not implemented properly it can cause issues in a multithreaded environment. It's important to use this pattern only when it is truly necessary.

No comments:

Post a Comment