mediumConceptCodingDesignMidSenior
How would you implement a singleton, and why do many teams treat it as an anti-pattern?
4 min readUpdated 2026-08-15
Answer
Short answer
The mechanics are easy - an enum in Java, a module-level value elsewhere - and are not the interesting part. The objection is that a singleton bundles two unrelated decisions, one instance and globally reachable, and the second is what makes dependencies invisible and tests order-dependent.
Was this answer helpful?
Likely follow-ups
- Why is double-checked locking broken without a memory barrier, and what fixes it?
- Your singleton reads configuration at class-initialisation time. What breaks in a test suite?
- How is a Spring singleton bean different from a classic singleton?
- When is a genuinely global single instance the right answer?
Related questions
- When is a factory the right answer, when is a builder, and when should you just call the constructor?mediumAlso on creational-patterns and singleton7 min
- What is the dependency inversion principle, and what exactly is being inverted?mediumAlso on testability3 min
- The business insists on a requirement that nobody can test — "the system must be intuitive". What do you write instead?mediumAlso on testability4 min
- A flash sale decrements stock from many threads. Do you go optimistic or pessimistic, and how do you prove nothing oversold?mediumSame kind of round: coding5 min