Singleton – Pattern or antipattern?

I have seen far too many CVs recently which just list every possible technology acronym, in no particular order.
The latest applicant also helpfully listed patterns, and the four listed included the well know Startegy and Singeleton patterns! At least this gave me a starting point for the interview!

When I ask about patterns in interviews, applicants usually start by describing the Singleton pattern, and I inwardly groan. There are so many reasons not to talk about Singleton, or at least if you do, to mention its limitations. In fact, it is now practically considered an antipattern.

Why Singleton is practically an antipattern:

  • Teams increasingly make use of IOC containers, and architectures geared towards allowing runtime dependencies to be switched out with mock implementations for testing. Hard coding a dependency to a Singleton object undermines all this effort, and reduces testability.
  • Singleton usage in Java may cause memory leaks. Since the reference to the singleon instance is held in static field, that singleton object, and any other resources it references, will be unavailable for garbage collection until the singleton Class instance itself is garbage collected, which is likely to be never, unless custom class loaders are used
  • Singleton classes cannot be extended, since the constructor is private. This can make it hard to reuse the logic contained in singleton classes, or adapt their behaviour to different environments


  • So, in summary, passing in a reference to an instance via a constructor or setter method is nearly always better and more flexible than accessing it using Singleton. If you find it is getting boring passing references to object instances around, consider using Spring, or a similar framework, to wire your application together declaratively, and remove the drudgery.


    You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

    AddThis Social Bookmark Button

    Leave a Reply