What's So Evil About Singletons?
Singletons might seem like a handy design pattern, but beware the hidden costs that tend to tag along during their implementation.
Join the DZone community and get the full member experience.
Join For FreeWe've all come across this word ‘singleton,’ and most of us even know the definition of it. As Wikipedia says, “Singletons are classes which have a restriction to have only one instance.”
Maybe a few of were lucky enough to use it, but believe me, even if you have used it, you might not know how evil it is.

But first of all, let me get everyone on the same page.
So to be more clear, “This pattern involves a single class which is responsible for creating an object while making sure that only one object gets created.”
Note: Most of the code is in Java, but it is so simple that anybody can understand it.
class Singleton {
private static Singleton INSTANCE = null;
private String criticalData;
private Singleton() {
criticalData = "This should be unique and state should be universal";
}
synchronized static Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}
public String getString() {
return this.criticalData;
}
public void setCriticalData(String value) {
criticalData = value;
}
}
By now, we know what a singleton class is and how it works. So where is the defect? Hint: The most obvious problem is hidden in line 7.
Since a synchronized block can be accessed one thread at a time, this might create a bottleneck for even getting the instance of the object.
But there are other, lesser-known problems.
Singletons and State
Singletons are enemies of unit testing. One of the major requirements of unit testing is that each test should be independent of others. This can cause tests to pass when, really, it's because they were called in a particular order
One Object Created
Isn’t it a complete violation of the Single Responsibility Principle, which states, “A class should have one, and only one, reason to change.” Basically, a class should not know whether it is a singleton or not. So if you want to limit the ability to instantiate, use the factory or builder patterns, which encapsulates creation. There, you can limit the number of objects to one or whatever you wish for.
‘Singleton’ is a fancy word for ‘global variable.’
Singletons Provide Global State
Exactly, that's why we have singletons. Yes. But at what cost? (Global variables were bad! Remember?) This provides a gateway to some service in your application so that we don’t have to pass around a reference to the service. The urge to create something global to avoid passing it around is a smell in your design.
Published at DZone with permission of Devendra Tiwari. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments