Singleton Pattern is type of Creational Design Pattern. Singleton pattern ensures a class has only one instance and provides a global point of access to it.

  • There are scenarios where you don’t want to allow anyone to create more than one object. In such cases Singleton Pattern helps to ensure that only one object is created even if someone tries to instantiate multiple times.

Steps to create Singleton Design Pattern

  1. Create Private Static Instance Variable : Create a private static variable to hold the single instance of the class. This variable should be static to ensure that there is only one instance shared among all instances of the class.
  2. Make the constructor “Private”: Do this to ensure no other class can create object of this class (as the constructor is private , it won’t allow someone to instantiate class from outside)
  3. Expose another public static method to return the instance: As the instantiation can’t be done from outside, we need to expose a method for the outside user to return the instance of the Singleton object. This method should also check if an instance of the class has already been created; if not, it should create it to allow only one object.
public class SingletonClass
{
   
  private static SingletonClass instance; 
   
 // Private constructor to prevent instantiation from outside
    private Singleton()
    {
       
    }
    public static Singleton GetInstance()
    {
        if (instance == null)
          {
            instance = new SingletonClass();
          }
    }
}

4. Make the Singleton Full Proof (Apply ThreadSafety): The above implementation is not thread-safe. In a multi-threaded environment, multiple threads could potentially create multiple instances of the Singleton class which defeats the purpose of creating Singleton Pattern. To ensure thread safety, you can use techniques like double-check locking or utilize the Lazy<T> class in C#.

public class SingletonClass
{
   
  private static SingletonClass instance; 
  private static readonly object lockObject = new object();
   
// Private constructor to prevent instantiation from outside
    private Singleton()
    {
       
    }
    public static Singleton GetInstance()
    {
         // Double-check locking for thread safety
        if (instance == null)
        {
            lock (lockObject)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

}

FAQ/ Interview Questions

1. What is the difference between Singleton and Static class?

  • A static class is implicitly sealed and cannot be instantiated. It is designed to hold static members such as methods, properties, fields, and events that can be accessed directly from the class itself, without creating an instance of the class.
  • Singleton provides more flexibility in managing its instance and allows for inheritance and interfaces. Static classes are sealed and cannot be inherited.
  • Singleton can maintain state and implement interfaces or extend base classes. Static classes are typically stateless and hold utility methods or constants.
  • Use Singleton when you need to manage global state, lazy initialization, or if the class represents a unique resource. Use static classes for grouping related utility methods or constants without the need for instantiation.

2. Where have you used Singleton Pattern? OR What is the real world usage of Singleton Pattern?

As a Logger: – You can implement Singleton logger to ensure there’s only one logger instance throughout the application, managing logs centrally.

Manage Configurations centrally– You don’t need to create multiple instances for the configurations, as it should remain same at the application level.

Database Connections: To maintain a pool of reusable database connections, reducing connection creation overhead.

Caching– To implement centralized cache management. I had implemented expiration policies, refresh mechanisms centrally.

At this point, you can be asked “Why can’t you do the same using static?” or “Static can do same thing

You need to explain why static is better . There could be many possible reasons that you need to explain with conviction.

  • Though static can also be used, I wanted to to control how and when the instance is created using lazy initialization and also had complex initialization logic . Static class is initialized automatically when the application starts . This limits flexibility in initialization timing.
  • I wanted to implement interface or extend a base class.
  • Static classes cannot implement interfaces or be inherited from, which limits its extensibility.
  • It is easy to mock.I can’t mock the static class. (Period, I don’t think any one can argue more )
  • Singleton can be injected into other classes, promoting loose coupling and facilitating dependency inversion principles. (this should seal the deal 🙂 )

Leave a Reply

Your email address will not be published. Required fields are marked *