Can you give me a few examples on when to use it ?
My general answer is "use it as rarely as possible". Singleton has so many drawbacks, many of them not immediately obvious, that using it is almost always a mistake. Search for Singleton in this forum to read some of the many discussions on this topic. In the great majority of cases, Singleton can straight-forwardly be replaced by creating a single instance and passing it around where needed ("dependency injection" often helps here).
Cases where Singleton might be appropriate include difficult cases such as accessing your external code inside a particularly constrained callback from opaque legacy software. But even then, if you can do it another way, the other way is probably better.
Use a singleton when you only need to have one instance running.
Also be sure that one, and only one instance will be created, and that peculiar classloader configurations and application packaging won't actually cause multiple instances to be created.
A singleton pattern is only the best pattern to use when it is better than all of the other alternatives.
Joined: Jan 07, 1999
Cameron McKenzie Use a singleton when you only need to have one instance running.
I guess I'd phrase that even more strongly. Something more like:
Only use a Singleton when there must only, ever, be one instance.
Turning a regular class into a Singleton is extra code and extra effort. If you are not sure if there might one day be a need for more than one instance, don't go to the extra effort of restricting it to be a Singleton. Leaving your options open by writing less code is a win/win scenario.
Originally posted by Cameron W. McKenzie: Use a singleton when you only need to have one instance running.
If you only need one instance, just create not more than one, that's my advice.
The Singleton pattern does more than ensuring the existance of just one instance:
- it puts that responsibilty inside the class itself (which means that it can't be reused in contexts where more instances would make sense), and
- it provides a global access point to that instance (with all the bad effects that globals have in general)
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus