Singleton Pattern
One instance of a class, reached from one place. Know how to build it safely, why interviewers treat it as a smell, and what to use instead.
Overview
The Singleton is one of the five creational patterns in the Gang of Four book (Gamma, Helm, Johnson and Vlissides, *Design Patterns*, 1994). Its job is small: make sure a class has exactly one instance, and give the whole program one way to reach it.
The classic build has three parts. The constructor is private, so nobody else can call it. A static field holds the one instance. A static accessor, usually called getInstance(), creates the instance the first time and returns the same object after that.
Interviewers ask about Singleton for two reasons. First, the thread-safety details show whether you understand initialization and memory ordering. Second, the pattern is widely criticized, and a strong answer names the costs (global state, hidden dependencies, hard tests) and offers the modern alternative: create one instance and inject it.
The shape of the pattern
Here are those three parts on a Config class that two services share.
Interview questions
- How do you make a Singleton thread-safe in Java?
- Why is Singleton often called an anti-pattern, and how would you fix code that uses one?
- When is a Singleton the right choice?
- What is the difference between a Singleton, a class with only static methods, and a DI-scoped singleton?
- What goes wrong with the new approach in Python, and what are the alternatives?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio