April 22nd, 2015
(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at: firstname.lastname@example.org
Everyone Loves Singleton
Why is the Singleton so attractive? I’ll be the first to admit: I liked it too. No, scratch that – I loved the Singleton. It felt like an old friend from the moment I laid eyes on it. It was simple and beautiful.
I’ll tell you why: it’s because the Singleton pattern is a throwback to non-OO programming. It’s a lifeline for people who didn’t understand a single word that the Gang of Four were trying to say. I don’t know how it got in there in the first place — some political OOPSLA pressure, no doubt — but it doesn’t belong in there. It’s Evil.
…Anyway, I liked Singleton for the same reason everyone does: it’s almost exactly the way I programmed back when I didn’t know jack squat about OOP. The only significant difference is that instead of having a file with a bunch of global functions in it, I have a file with a CLASS that has a bunch of global functions. No need to worry my little head about how many of them to have, since you only need one! It’s OOP made easy.
The standard justification for Singleton is: “Use this pattern whenever it’s clear that you will only ever need ONE instance of this class at a time.” The example they use in Design Patterns is a print spooler. Obviously you’ll only ever need one of those, so you should make it a Singleton, right?
Unless you need another one with different behavior, that is. But seeing as how that could never ever possibly happen, we might as well go ahead and make it a Singleton. After all, a gang of four guys can’t be wrong!
…Whoo! My client code (by which I mean anyone in the same process using the Singleton instance) no longer needed to do that extra getInstance() call, which was just plain annoying and useless.
But why stop there? Why not just get rid of the delegation altogether? I resolved to figure this out, and hopped on the patterns newsgroups where Ralph Johnson lurked. Lo and behold, Ralph had answered that very question the month before. His answer: it doesn’t matter; using static methods is fine – that’s still a Singleton.
Great! Gosh, I was excited. I’d get rid of the Singleton instance (and the boilerplate), make everything static, and my code was now super clean.
Yep. I was using classes purely as namespaces.
Since in Java, classes are the ONLY globally available namespace mechanism built into the language, this is actually a common thing to do, Singleton or no. Unless you want to build your own reflective registry, or use JNDI or something, classes are your only option for separating your code into namespaces. So in that regard, the (very) little I was doing with classes wasn’t actually so wrong.
But I’d thrown all the rest of that OO crap out the window. It was a C program with some namespace support and garbage collection.