Why do many developers call Singleton an anti-pattern?
It is global state in disguise: hidden dependencies, hard-to-reset state between tests, tight coupling to one concrete class, and trouble when you later need two instances.
Explain it simply
A single shared notice board at the college gate is handy, but if anyone can write on it and no one knows who relies on it, a change in one corner surprises everybody else. The code that reads from a Singleton looks independent but silently depends on shared state.
Example
class OrderService {
void place(Order o) {
// Hidden dependency: not in the constructor, not in the signature
Database.getInstance().save(o);
}
}Problems:
- A test for
placecannot easily swap in a fake database, becausegetInstance()is fixed. - State left by one test (rows saved, flags set) leaks into the next.
- Running tests in parallel may clash on the shared object.
- If you later need one database per tenant, every caller must change.
Better: create one object in main and pass it in. You keep "only one instance" as a decision of the wiring code, not as a rule enforced by the class.
What to say in the interview
"Singleton introduces hidden global state and coupling that hurt testability and flexibility. When I only need one instance, I create it once at startup and inject it, instead of letting the class enforce its own uniqueness."
Common mistakes
- Concluding Singleton is always wrong. A logger or read-only config can be a reasonable use.