Introduction
Singleton Design pattern falls under creational design pattern. Its main purpose is to restrict the instantiation of a class to one object. This is very useful when exactly one object is needed to coordinate the action across the system.
It is very useful in a situation where various parts of an application concurrently try to access a shared resource. An example of shared resources would be Logger, Printer, Spooler etc.
Points to keep in mind before creating Singleton Design Pattern
The following points should be kept in mind before the creation of Singleton Design Pattern.
- Singleton Classes must be memory-leak free because its instance is created once and it remains for the lifetime of the application.
- Singleton class should not be easily extensible.
- Always implement Singleton class with Interface because it helps in unit testing, especially with Dependency Injection.
Singleton is often preferred to global variable
Singleton is always preferred over global variables due to the below advantages.
- Singleton does not pollute the global namespace with unnecessary variables.
- Singleton permits lazy allocation and initialization, whereas Global variables in many languages will always consume resources.
Bad Points about Singleton Design Pattern
Below are some disadvantages of using Singleton Design Pattern.
- Singleton deviates from the Single Responsibility Principle.
A Singleton class has responsibility to create an instance of it, along with other business responsibilities.
Solution
This issue can be solved by delegating the creation part to Factory Object.
- A Singleton class can't be Sub-Classed.
- Singleton can hide dependencies.
Singleton class provides a way in which its constructor can't expect any parameter. Its object creation part is invisible. It limits the flexibility of the program.
Solution
Developers can use the idea of Dependency Injection to overcome this issue. When Dependency Injection is used, Singleton instance is not retrieved inside the class but is passed through the constructor or a property like below,
- ICalculate calculateObj= Singleton.Instance;
-
- SingletonClient singleton = new SingletonClient(calculateObj);
- singleton.AddOperation(10,20);
In the above example, Constructor of SingletonClient accepts parameter of type ICalculate. It can be the real singleton instance or a mock object.
Question - How can we get instance from Singleton class with Reflection?
Answer - I would like to create instance of Singleton class like the below code.
- var singleton = typeof(Test).GetProperty("Instance").GetValue(null);
- Implement a Singleton Design Pattern and make it safe over the Reflection API, and how do you save it while cloning it?
Answer - Use a Static Constructor and make your Singleton a "Read Only" property.
Conclusion - Singleton is considered one of the worst design patterns, but along with all those points, it also has some advantages.