What is the Singleton pattern, and what are its drawbacks?
EasyConceptDesign Patterns
Answer
The Singleton pattern ensures that a class has exactly one instance and provides a global access point to it. It suits shared resources such as a configuration registry or a connection pool.
public class Config {
private static final Config INSTANCE = new Config();
private Config() {}
public static Config getInstance() { return INSTANCE; }
}
- Thread safety: eager initialisation as above, a static holder class or an
enumare safe; lazy initialisation needs double-checked locking on avolatilefield. - Drawbacks: it is global mutable state, hides dependencies, makes unit testing and mocking harder, and can become a contention point.
- Prefer creating one instance at startup and passing it in through dependency injection.
More in Design Patterns
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | What is the Singleton pattern, and what are its drawbacks? | Concept | Easy | Read the answer to What is the Singleton pattern, and what are its drawbacks? | |||
| 2 | What is the Factory pattern, and when would you use it? | Concept | Medium | Read the answer to What is the Factory pattern, and when would you use it? | |||
| 3 | How does the Observer pattern work, and where is it used? | Concept | Medium | Read the answer to How does the Observer pattern work, and where is it used? | |||
| 4 | What is the Strategy pattern, and how does it differ from the State pattern? | Concept | Medium | Read the answer to What is the Strategy pattern, and how does it differ from the State pattern? |