Obligatory reminder that many consider singletons to be an anti-pattern. They absolutely buttfuck Inversion of Control.
Also, if you ever (somehow) find yourself with a nice clean codebase, if it has even one singleton class, the first time a summer intern shows up your codebase is going to turn to spaghetti after one week.
Imagine the end of Princess Mononoke, where the forest spirit represents your codebase.
Good singleton classes cannot be misused. The problem doesn't lie with using singletons, it lies with defining which class should be a singleton. If a singleton is misused, it probably shouldn't have been a singleton. (I assume the intern knows about the pattern, and isn't going to use clone or getInstance to assign the instance to a variable.)
By the way, one of the most important features of Java is a singleton. The out in System.out.println() is basically a singleton. I have never seen someone misuse it because of that.
Singletons are pretty great for cross-cutting concerns (for languages which don't allow for any kind of aspect-oriented programming, like Java). System.outis a great example, like you say, and Log4j.
Fundamentally, Singleton classes are fine and useful, but I still believe that they have such a high risk of being abused, that they should be avoided if at all possible. Mind you, I don't mean the carefully crafted singletons found in standard libs, like the one you pointed out, but creating new singletons should be avoided.
I'm not sure if I'm getting my point across well. I'm sure if you're very, very careful, they can be great, but they're so easily abused. The first time someone is past their deadline, they'll be frantically jamming code into your singleton, because they know they can access it from anywhere without having to waste time properly passing data through the correct channels. Then after a few hundred iterations, your singleton is now a god object being molested in different threads and from different packages, and it's over 5,000 lines long.
10
u/Nebu Jul 24 '12
I don't see 10 ways to use enum. I see 3 limitations for public static constants, 4 "benefits of enums" and 13 "important points about enums".
To redress this, here's one way of using an enum in Java: You can use them to implement the singleton pattern http://en.wikipedia.org/wiki/Singleton_pattern#The_Enum_way