Design Pattern — Singleton
A detailed discussion on most common Design pattern — Singleton
Singleton is the most commonly used design pattern — and for good reason. It is simple to understand and it solves a well-defined problem in Software Engineering.
What is Singleton Design pattern?
Singleton is one of the Gang of Four(GoF) design patterns. It is a creational design pattern, meaning it deals with the creation of the object.
In a scenario when you need exactly one object of a class, you would use Singleton. Singleton restricts the creation of objects of the said class to only one. This single instance can be important to coordinate actions across the system or guarantee control of resources. It has global access in your application.
In the Singleton design pattern, the class is responsible for creating itself and managing its own lifecycle. The sole instance of the class is stored in a private static member of the class. This instance is however available outside class via a public getter.
Examples
Instances where you might have seen or used Singleton —
- Java — Runtime & SecurityManager in Java are examples of Singleton classes in Java APIs. Following is how you access their instances —
- Database manager, in-memory cache or Loggers are generally created as Singleton. They provide a way to share the resources — database or memory or logging buffer respectively.
- State object pattern is generally Singleton. You can read more about the State pattern here.
Problems addressed by Singleton
- It ensures the class has only one instance — and restricts the creation of any more
- The only instance of the class can be accessed globally via a public getter
- Singleton class controls its own instantiation and lifecycle
These problems are addressed by having a private constructor, public getter and shared static instance. Continue reading for details.
UML for Singleton
This discussion will be incomplete without a UML diagram about this Design pattern -
Client is a class which uses the SingletonService. SingletonService has a shared instance ‘instance’. It also has a public getter getInstance(). It’s constructor is private.
Creating a Singleton Class
Here is how you would create a simple Singleton class.
This is a very simple way to create a Singleton class. I have explained each line below. Notice the number of the list below corresponds to comment in the code above.
- #1 — This is the name of the package. It could be different in your case based on the project and the package you use.
- #2 — Here we specify the name of the Singleton class. In my case it is SingletonClass.
- #3 — Here I have created an instance of the SingletonClass. This instance is stored in a private & static member sharedInstance. The name of the member indicates that it is a shared instance. This is a common practice to name the shared instance as sharedInstance or sharedLocationManager as the case may be.
- #4 — To make sure only one instance of the SingletonClass is created, the constructor is marked as private. If we try to instantiate this class, it will throw an error. See the error message below.
- #5 — Finally we need a public getter for the sharedInstance. This is the method which will be used to provide an instance of the Singleton class. See code how we can use this getter to get the instance of the Singleton class.
There is a small problem with the implementation of Singleton above. Even if we do not need the Singleton class, the class is still initialized. There is a better way to handle this. Enter ‘Lazy-loading’.
Lazy loading
In comment #3, we see the shared singleton instance is created when the class is loaded. So even if you are not going to use the Singleton class in your code, the shared object is created.
A better approach is to use lazy loading, i.e. not create the instance of the Singleton class until it is needed. Refer the code for the same below -
If you compare this block of code with the one above, you will notice that we not instantiating the class in #3. We have a null check in the getSharedInstance() method in #5. If the sharedInstance is null, we instantiate the class. This approach is called Lazy-loading as the object is not initialized unless we try to use it. This approach is preferred over the previous one.
Private constructor
If you see the code blocks above, you would notice the default constructor is marked as private. This is to make sure the class cannot be instantiated from outside. Singleton class is responsible for its own initialization. There should be just one instance of the class which should be accessible globally in the app via a public getter. Private constructor stops us from creating another instance of the Singleton class from outside.
Get Vivek Mittal’s stories in your inbox
Join Medium for free to get updates from this writer.
However, even with the private constructor, an instance of the Singleton class can be created using Reflection. We can discuss this in future posts.
Thread safety
The solutions mentioned above are sufficient when we have just one thread in our application. In a situation when our Singleton class can be used across threads, we need to make sure our class is thread-safe. To achieve this we can just add a synchronized block before we instantiate the Singleton object.
The getSharedInstance() method is now modified as shown above. Notice we have added synchronized block at #8. The second important change is the addition of the keyword volatile to the static member. This is because we just want to make sure not two threads when accessing the singleton instance try to instantiate it.
If the singleton instance is already created no need to create it and all the threads can get that instance. In the scenario where sharedInstance is not created and one thread tries to create that instance, we do not want any other thread to try and do the same thing. That is why we have a synchronized block after checking for null.
This is called Double-checked Singleton, as we check for null twice to make sure it is thread-safe. This is the most common and widely accepted approach to create Singleton classes.
When to use Singleton?
You can use Singleton in the following scenarios —
- Used with other design patterns — Singleton is often used alongside other patterns like Facade and Factory, where you want exactly one instance managing the creation or access layer.
- Access to Hardware or common resource — You may be accessing specific hardware from your project. It makes sense to have all operations on the said hardware/resource handled through a single class. Initialization on such resources can be expensive. Common examples — Database, in-memory Cache, Robotic arm.
- Replacement of Global variables — Singleton is preferred over global variables because it provides controlled access through a getter, supports lazy initialization, and can enforce thread safety — none of which a raw global variable offers.
- Global access to instance — Sometimes the project needs to store important data and have it accessible across the application. Singleton provides this through a public getter while maintaining control over the lifecycle of the instance.
Issues with Singleton
- Overused — Owing to its simplicity and power, it is overused. You should always evaluate if the class really need to be Singleton.
- Slowness — If you make everything Singleton, it will slow your application.
- Difficult to unit test — Singletons have a private constructor and are not programmed on an interface, they are difficult to unit test. This may seem insignificant but is a big concern.
- Thread safety — If not implemented properly, Singleton classes may not be thread-safe. Double-check implementation we saw above is a thread-safe implementation.
- No parameter — Singleton cannot take parameters, if it takes a parameter, it is not a Singleton. It becomes a Factory design pattern. At any time, you see your Singleton class accepting parameter, you should re-think and re-evaluate the design.
- Violates the Single Responsibility Principle — The Singleton class does two things at one time, which violates the Single responsibility principle.
- Code smell — Singleton can be masking some bad design under its sleeves. We should be sure if we really need a singleton. Taking a step back and re-evaluating our design can help. We should see if we can solve the same problem without the use of Singleton.
Summary
- Guarantees one instance. This Singleton instance is stored in a private static member but is accessible via a public getter.
- Simple to implement and use.
- Thread-safe.
- Solves an important problem/well-defined problem.
- Often abused/overused.
Singleton as an Anti-pattern
Some Jedi of Software Engineering consider Singleton design pattern as an Anti-Pattern. The argument is that it creates more problems than it solves — the restriction of having only one object is often unnecessary, and it makes the object globally accessible, which hinders testability and introduces hidden dependencies. This is a debate worth understanding, even if you use Singleton regularly.
Conclusion
Singleton is powerful, easy to understand, and easy to implement. It solves a commonly occurring design problem.
On the flip-side, it is a design pattern which is overused. Engineers who learn it try to apply it at every opportunity they get. Singleton classes are difficult to unit test and violate the Single Responsibility Principle.
There are both pros and cons to this design pattern. Be mindful when you use it.
Written & edited by — Vivek Mittal
https://www.linkedin.com/in/vivekmittal06/
Additional reading
- Design Pattern — Strategy
- Leader Election — Cloud Design Pattern
- Sidecar — Cloud Design Pattern








