Fixing the Singleton

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.

Share:
  • DZone
  • Digg
  • del.icio.us
  • Reddit
  • Facebook
  • Twitter