As others said:
- Singletones are global variables with a different name.
- Singletones are usually a bad idea.
- Singletones can be replaced with "monostate" classes - classes that seem to have the usual build / destroy semantics, but all have the same state.
Please note that, in my opinion, “static classes” are usually also a bad idea, a hacker workaround for a language that does not allow free functions, or for sharing a state between many functions, not wanting to pass this state as a parameter.
In my experience, almost all projects with single or static classes can be turned into something better, more understandable and flexible, getting rid of these designs.
Edit: on request why most singletons are global variables with a different name.
In most languages that I know, most singleton classes are accessible through a static member function of this class. A single instance is available for all code that has access to the definition of the singleton class. This is a global variable - all the code that the class includes can make changes to one instance of your singlet.
If you are not using a static member function (or some static factory method that has the same consequences), but instead pass the singleton object to all the clients that need it, then you won't need the singleton template, just execute the same object for all clients.
Joris Timmermans Mar 31 '10 at 7:42 2010-03-31 07:42
source share