Quick On Singleton Design Pattern

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.
Quick On Singleton Design Pattern
 
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
  1. public sealed class SingletonLogger {  
  2.     private static readonly Lazy<SingletonLogger> _singletonLoggerObj = new Lazy<SingletonLogger> (() => new SingletonLogger());  
  3.     private SingletonLogger() {}  
  4.     public static SingletonLogger SingletonLoggerInstance {  
  5.         get {  
  6.             return _singletonLoggerObj.Value;  
  7.         }  
  8.     }  
  9. }  
Client Code

  1. List<int> hashData = new List<int>();  
  2. for (int index = 0; index < 10; index++)
  3.     hashData.Add(SingletonLogger.SingletonLoggerInstance.GetHashCode());  

  4. if (hashData.Distinct().Count() == 1)
  5.      Console.WriteLine("I am Singleton!");  
  6. else
  7.      Console.WriteLine("I am not Singleton!");  
Output
 
Quick On Singleton Design Pattern
 
Option B
 
When multiple parallel threads access the same instance at the same time to get an instance of a singleton logger, there may be a concurrency conflict on creating an instance and violating the singleton pattern.
 
The below code defines the singleton code for Logger that is thread-safe. When multiple parallel threads access code at the same time to get an instance of a singleton logger. The code defines a lock pad object to prevent the concurrency issue while creating a singleton instance.
 
Implementation Code
  1. public sealed class SingletonLoggerThreadSafe {  
  2.     private static readonly object _objLock = new object();  
  3.     private static SingletonLoggerThreadSafe _instance = null;  
  4.     private SingletonLoggerThreadSafe() {}  
  5.     public static SingletonLoggerThreadSafe Instance {  
  6.         get {  
  7.             if (_instance == null) {  
  8.                 lock(_objLock) {  
  9.                     if (_instance == null)
  10.                         _instance = new SingletonLoggerThreadSafe();  
  11.                 }  
  12.             }  
  13.             return _instance;  
  14.         }  
  15.     }  
  16. }  
Client Code
  1. static void Main(string[] args) {  
  2.     // By using - SingletonLoggerThreadSafe  
  3.     Task<int> task1 = Task.Run(ThreadBatch1);  
  4.     Task<int> task2 = Task.Run(ThreadBatch2);  
  5.     if (task1.Result == task2.Result && task1.Result != -1)
  6.         Console.WriteLine("I am Singleton!");  
  7.     else
  8.         Console.WriteLine("I am not Singleton!");
  9.  
  10.     Console.ReadLine();  
  11. }  
  12. public static int ThreadBatch1() {  
  13.     int val = -1;  
  14.     List<int> hashData = new List<int> ();  
  15.     for (int index = 0; index < 50000000; index++)
  16.          hashData.Add(SingletonLoggerThreadSafe.Instance.GetHashCode()); 

  17.     var res = hashData.Distinct();  
  18.     if (res.Count() == 1) {  
  19.         Console.WriteLine("ThreadBatch1 - I am Singleton!");  
  20.         val = res.First();  
  21.     } 
  22.     else
  23.         Console.WriteLine("ThreadBatch1 - I am not Singleton!");  
  24.     return val;  
  25. }  
  26. public static int ThreadBatch2() {  
  27.     int val = -1;  
  28.     List<int> hashData = new List<int>();  
  29.     for (int index = 0; index < 50000000; index++)
  30.         hashData.Add(SingletonLoggerThreadSafe.Instance.GetHashCode()); 

  31.     var res = hashData.Distinct();  
  32.     if (res.Count() == 1) {  
  33.         Console.WriteLine("ThreadBatch2 - I am Singleton!");  
  34.         val = res.First();  
  35.     }
  36.     else
  37.         Console.WriteLine("ThreadBatch2 - I am not Singleton!");  
  38.     return val;  
  39. }  
Output
 
Quick On Singleton Design Pattern 
 

Conclusion

 
Both of the above options are recommended. Personally, I would prefer Option A that takes advantage of lazy initialization.
 
Note
This is one of the common design patterns interviewers as in design pattern interview questions. 😊