The most common argument against using singletons can be summarised in this quote:
When you mention singletons it’s common to get a dismissive reply, something in the lines of “singletons are only glorified global variables”.
This is not unlike how I have treated suggestions to use the singleton design pattern as a solution to a problem. However, there are good uses of the pattern too, and in this post I outline one of them.
The singleton design pattern isn’t so much about only having one instance of a class as it is about providing control over the instantiation of a class.
This slight shift in focus is important, because if you put the emphasis on having one instance, you’re in the global variable mess, and you don’t want to be there.
The quote above is true if you litter your code with code like this:
This is exactly the same as having a global variable. It can make your application harder to debug, it will definitely make it harder to understand your code and your application will be more fragile and harder to change.
However, looking at the instantiation control aspect of singleton we can see that you don’t have to use a singleton in way of the example above. Just because there is global access point to the singleton doesn’t mean you have to use it everywhere. Instead, use
getInstance() once, and then pass the object around as you would any other object.
foo = Foo.getInstance();
bar.setFoo(foo); baz.setFoo(foo); // ...
baz in the example above don’t know that
Foo is a singleton, and neither do they need to know. They know only that they get passed an object which they can use and no more.
The benefit of this is that if you later decide that
Foo doesn’t need to be a singleton anymore – perhaps you want to have exactly two instances, or a pool of instances, the only code you need to change is the part where you get the instance, the rest of your application just doesn’t care.