C# Singleton Pattern

Featured image

Git Source


Singleton Pattern πŸ‘€

1 - UnsafeSingleton

class UnsafeSingleton : Singleton
{ 
	private static UnsafeSingleton _instance;

	public static UnsafeSingleton Instance
	{
		get
		{
			if (_instance is null)
			{
				_instance = new UnsafeSingleton();
			}

			return _instance;
		}
	} 

	protected UnsafeSingleton() => Console.WriteLine("Create UnsafeSingleton instance!!"); 
}

2 - SafeSingleton

class SafeSingleton : Singleton
{
	private static object _thislock = new object();
	private static SafeSingleton _instance;

	public static SafeSingleton Instance
	{
		get
		{
			lock (_thislock)
			{
				if (_instance is null)
				{
					_instance = new SafeSingleton();
				}
			}

			return _instance;
		}
	}

	protected SafeSingleton() => Console.WriteLine("Create SafeSingleton instance!!"); 
}

3 - DCLSingleton

//Double Checked Locking
class DCLSingleton : Singleton
{
	private static object _thislock = new object();
	private static DCLSingleton _instance;

	public static DCLSingleton Instance
	{
		get
		{
			if (_instance is null)
			{
				lock (_thislock)
				{
					if (_instance is null)
					{
						_instance = new DCLSingleton();
					}
				}
			}

			return _instance;
		}
	}

	protected DCLSingleton() => Console.WriteLine("Create DCLSingleton instance!!"); 
}

4 - StaticSingleton

    class StaticSingleton : Singleton
    {
        private static readonly StaticSingleton _instance;

        static StaticSingleton()
        {
            _instance = new StaticSingleton();
        }

        public static StaticSingleton Instance => _instance;

        protected StaticSingleton() => Console.WriteLine("Create StaticSingleton instance!!"); 
    }

5 - LazySingleton

class LazySingleton : Singleton
{
	private static readonly Lazy<LazySingleton> _instance = new Lazy<LazySingleton>(() => new LazySingleton());

	public static LazySingleton Instance => _instance.Value;

	protected LazySingleton() => Console.WriteLine("Create LazySingleton instance!!"); 
} 

singleton