Creational Patterns Interview Questions
Common design pattern interview questions covering Singleton and other creational patterns, with detailed answers.
Video Tutorial Coming Soon — Channel Production Underway
1. What problem does the Singleton pattern solve?easy
It ensures a class has exactly one instance throughout the application's lifetime, with one global access point to it — useful for shared resources like configuration managers, connection pools, or loggers, where having multiple instances would cause bugs or waste resources.
2. How do you make a Singleton implementation thread-safe?medium
Use double-checked locking: check if the instance is null, and only then enter a synchronized block to check again before creating it. The second check prevents two threads that both passed the first check from creating two separate instances.
public class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}The volatile keyword matters too — without it, a thread could see a partially-constructed instance due to instruction reordering.
3. What's a downside of the Singleton pattern that interviewers often ask about?medium
Singletons introduce global state, which makes unit testing harder (tests can't easily swap in a mock instance) and can hide dependencies — a class using a Singleton doesn't declare that dependency in its constructor, making the codebase's real dependency graph less obvious. Overuse of Singleton is often considered an anti-pattern for exactly this reason.
4. How is Singleton different from just using static methods on a class?hard
A Singleton is a real object instance — it can implement interfaces, be passed around as a reference, hold instance state that's initialized lazily, and participate in polymorphism. A class of pure static methods can do none of this: it can't implement an interface's instance methods, can't be lazily constructed with real initialization logic, and can't be substituted with a different implementation (e.g. for testing) the way an injected Singleton reference sometimes can.