Edit: From another question I provided an answer that has links to a lot of questions/answers about singletons: More info about singletons here:
So I have read th
Singletons basically let you have complex global state in languages which otherwise make it difficult or impossible to have complex global variables.
Java in particular uses singletons as a replacement for global variables, since everything must be contained within a class. The closest it comes to global variables are public static variables, which may be used as if they were global with import static
C++ does have global variables, but the order in which constructors of global class variables are invoked is undefined. As such, a singleton lets you defer the creation of a global variable until the first time that variable is needed.
Languages such as Python and Ruby use singletons very little because you can use global variables within a module instead.
So when is it good/bad to use a singleton? Pretty much exactly when it would be good/bad to use a global variable.
I use Singletons as an interview test.
When I ask a developer to name some design patterns, if all they can name is Singleton, they're not hired.
Most people use singletons when they are trying to make themselves feel good about using a global variable. There are legitimate uses, but most of the time when people use them, the fact that there can only be one instance is just a trivial fact compared to the fact that it's globally accessible.
Answer:
Use a Singleton if:
Do not use a Singleton if:
How to create the best singleton:
As others have noted, major downsides to singletons include the inability to extend them, and losing the power to instantiate more than one instance, e.g. for testing purposes.
Some useful aspects of singletons:
However, you don't have to use a singleton to get these benefits. You can write a normal object that does the work, and then have people access it via a factory (a separate object). The factory can worry about only instantiating one, and reusing it, etc., if need be. Also, if you program to an interface rather than a concrete class, the factory can use strategies, i.e. you can switch in and out various implementations of the interface.
Finally, a factory lends itself to dependency injection technologies like Spring etc.
In desktop apps (I know, only us dinosaurs write these anymore!) they are essential for getting relatively unchanging global application settings - the user language, path to help files, user preferences etc which would otherwise have to propogate into every class and every dialog.
Edit - of course these should be read-only !