Over a million developers have joined DZone.

Fixing the Singleton

DZone's Guide to

Fixing the Singleton

· Java Zone ·
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

When you ask people who know almost, but not completely nothing about patterns, about software design patterns, they probably bring up the singleton pattern. It’s extremely easy: Just make sure you have one single instance of a class.

If you ask more experienced developers about the singleton, they will probably tell you its bad and should be avoided.

What is so bad about the singleton that it fell from the heavon of patterns into the hell of anti patterns?

If you check the description of the singleton pattern in the Gang of Four book it talks about two characteristics of the singleton:

  • There can be only  a single instance
  • There is a central access point to that instance

And there really is nothing wrong about the first point. Sometimes you really can’t have more then one instance, but even if multiple instances don’t hurt, if they don’t give you any benefit (i.e. if they are stateless) you might as well reuse a single instance.

The problem is really with the central access point. This makes the singleton look and behave like a global variable. And how should we obtain our dependencies? Correct through Dependency injection.

So the next time you think: “Looks like a singleton to me”. Go ahead, create a singleton. But also create an interface which gets implemented by the singleton and make it very clear that nobody may use this singleton except via its interface and dependency injection through constructor.


From http://blog.schauderhaft.de/2012/01/22/fixing-the-singleton/

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}