Singleton pattern design in c#

The Singleton pattern is a design pattern that ensures a class has only one instance and provides a global point of access to it. This pattern is useful when you need a single instance of a class to coordinate actions across the system.

Here are some common ways to create a Singleton pattern class in C#:

1. Lazy Initialization (Lazy Singleton):

This approach initializes the Singleton instance when it is first accessed. It utilizes the Lazy<T> type provided by the .NET Framework to implement thread-safe lazy initialization.

public class Singleton
{
    private static readonly Lazy<Singleton> lazyInstance = new Lazy<Singleton>(() => new Singleton());

    public static Singleton Instance => lazyInstance.Value;

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

    public void SomeMethod()
    {
        // ...
    }
}

2. Eager Initialization (Eager Singleton):

This approach initializes the Singleton instance when the application starts. Since static members are initialized when the class is loaded, this method is inherently thread-safe.

public class Singleton
{
    private static readonly Singleton instance = new Singleton();

    public static Singleton Instance => instance;

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

    public void SomeMethod()
    {
        // ...
    }
}

3. Double-Check Locking:

This approach combines the benefits of both lazy and eager initialization. It uses double-check locking to ensure thread safety while minimizing synchronization overhead.

public class Singleton
{
    private static volatile Singleton instance;
    private static readonly object syncRoot = new object();

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

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

    public void SomeMethod()
    {
        // ...
    }
}

Each of these methods can be used to implement the Singleton pattern, but they have different characteristics in terms of performance and thread safety. In a real-world project, you can choose the appropriate implementation based on your requirements. In most cases, Lazy Initialization (Lazy Singleton) is a simple and efficient choice.

评论区 0