Over a million developers have joined DZone.

Fixing the Singleton

· Java Zone

Discover how AppDynamics steps in to upgrade your performance game and prevent your enterprise from these top 10 Java performance problems, brought to you in partnership with AppDynamics.

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/

The Java Zone is brought to you in partnership with AppDynamics. AppDynamics helps you gain the fundamentals behind application performance, and implement best practices so you can proactively analyze and act on performance problems as they arise, and more specifically with your Java applications. Start a Free Trial.

Topics:

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

{{ parent.tldr }}

{{ parent.urlSource.name }}