Design patterns Singleton Singleton (C#)


Example

Singletons are used to ensure that only one instance of an object is being created. The singleton allows only a single instance of itself to be created which means it controls its creation. The singleton is one of the Gang of Four design patterns and is a creational pattern.

Thread-Safe Singleton Pattern

public sealed class Singleton
{
    private static Singleton _instance;
    private static object _lock = new object();
 
    private Singleton()
    {
    }
 
    public static Singleton GetSingleton()
    {
        if (_instance == null)
        {
             CreateSingleton();
        }

        return _instance;
    }

    private static void CreateSingleton()
    {
        lock (_lock )
        {
            if (_instance == null)
            {
                 _instance = new Singleton();
            }
        }
    }
}

Jon Skeet provides the following implementation for a lazy, thread-safe singleton:

public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy =
        new Lazy<Singleton>(() => new Singleton());
    
    public static Singleton Instance { get { return lazy.Value; } }

    private Singleton()
    {
    }
}