What is Singleton Design Pattern?
A singleton design pattern is a creational design pattern. It is used to maintain a single instance throughout the application.
When to use a Single Design Pattern?
When our requirement requires a single instance through the application and if it has to be inherited by some other interface/class or if memory management should be dynamic we can take steps to implement this design pattern.
If our aim is to create only a single instance I recommend using a static class.
Where we can use it?
For Database connection, logging, caching purposes, etc.
Rules to implement Singleton
- It should have Global access
- It should not be inherited by some other class; i.e., we have to seal the class with a sealed keyword / we can make the constructor private to stop inheritance.
- Constructor should be Private, to prevent the creation of instances from outside the class. And once we define the constructor as private it will also help to stop being inherited.
Below is the code that defined the Singleton design pattern. The below code is not thread-safe.
namespace Singleton.Design.Pattern
{
public class SingletonSample
{
private static SingletonSample _instance;
/// <summary>
/// Instance will set only once initially when _instance is null
/// </summary>
public static SingletonSample Instance => _instance = _instance ?? new SingletonSample();
/// <summary>
/// To prevent inheritance of this class and to prevent the creation of instance from outside the class
/// </summary>
private SingletonSample()
{
}
}
}
Below is the code for accessing singleton instances. To make sure we have a single instance, I am accessing the class with Instance 10 times and matching with some resistance object, along with printing object reference hash code
using System.Collections.Generic;
using static System.Console;
namespace Singleton.Design.Pattern
{
class Program
{
public static void Main()
{
List<SingletonSample> instances = new List<SingletonSample>();
for (int i = 0; i < 10; i++)
{
instances.Add(SingletonSample.Instance);
}
var refInstance = SingletonSample.Instance;
WriteLine($"Object refInstance Hash code:{refInstance.GetHashCode()}");
foreach (var instance in instances)
{
if (instance.Equals(refInstance))
WriteLine($"Found same object with Hash code:{instance.GetHashCode()}");
else
WriteLine($"Found mismatch object with Hash code:{instance.GetHashCode()}");
}
ReadLine();
}
}
}
Below is the output window after the execution of the above code.



Sourav Kumar DasPosted Dec 26, 2019, 12:48 AM
Nice and useful article. Thanks for sharing.