Singleton Design Pattern is a creational design pattern. It is one of the common design patterns used to design software applications.
What is Singleton Design Pattern?
- Singleton term represents a single instance.
- Singleton design pattern ensures to have only one instance of the object in the application life cycle.
- Here are the few examples as below,
- Real World - The Sun, The Earth, The Moon, A CEO
- Software World – Logger, Connection, File, Database context etc.
Basic needs of Singleton Design Pattern?
- Rule 1: Class should not be inheritable, mark class with ‘sealed’ keyword.
- Rule 2: Class should not be instantiated by caller classes. Define private constructor in the class only.
- Rule 3: Class should have static properties, mark properties with a ‘static’ keyword to make them static.
- Rule 4: Class should be accessible anywhere/globally, mark class as ‘public’ keyword.

Advantages
- It prevents call code to create new instances of the class
- A single instance of an object is used and available to the application to use class's functionality.
Disadvantages
- Unit testing is very hard, we cannot run multiple tests in parallel.
- Cannot completely isolate the classes that are dependent on the singleton.
How to implement it?
There are many ways to implement a singleton design pattern. Here, I will demonstrate the best practices to implement a singleton design pattern.
Option A
Below code defines the singleton code for Logger by using .NET Lazy type. The initialization of the object happens on demand only. The caller code calls the singleton logger with 10 times and has the same instance all the 10 times call with having the same hash code.
Implementation Code
public sealed class SingletonLogger {
private static readonly Lazy<SingletonLogger> _singletonLoggerObj = new Lazy<SingletonLogger> (() => new SingletonLogger());
private SingletonLogger() {}
public static SingletonLogger SingletonLoggerInstance {
get {
return _singletonLoggerObj.Value;
}
}
}
Client Code
List<int> hashData = new List<int>();
for (int index = 0; index < 10; index++)
hashData.Add(SingletonLogger.SingletonLoggerInstance.GetHashCode());
if (hashData.Distinct().Count() == 1)
Console.WriteLine("I am Singleton!");
else
Console.WriteLine("I am not Singleton!"); 


Join the conversation! Your thoughts help the community grow.