Singleton: How should it be used
- by Loki Astari
Edit:
From another question I provided an answer that has links to a lot of questions/answers about singeltons: More info about singletons here:
So I have read the thread Singletons: good design or a crutch?
And the argument still rages.
I see Singletons as a Design Pattern (good and bad).
The problem with Singleton is not the Pattern but rather the users (sorry everybody). Everybody and their father thinks they can implement one correctly (and from the many interviews I have done, most people can't). Also because everybody thinks they can implement a correct Singleton they abuse the Pattern and use it in situations that are not appropriate (replacing global variables with Singletons!).
So the main questions that need to be answered are:
When should you use a Singleton
How do you implement a Singleton correctly
My hope for this article is that we can collect together in a single place (rather than having to google and search multiple sites) an authoritative source of when (and then how) to use a Singleton correctly. Also appropriate would be a list of Anti-Usages and common bad implementations explaining why they fail to work and for good implementations their weaknesses.
So get the ball rolling:
I will hold my hand up and say this is what I use but probably has problems.
I like "Scott Myers" handling of the subject in his books "Effective C++"
Good Situations to use Singletons (not many):
Logging frameworks
Thread recycling pools
/*
* C++ Singleton
* Limitation: Single Threaded Design
* See: http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf
* For problems associated with locking in multi threaded applications
*
* Limitation:
* If you use this Singleton (A) within a destructor of another Singleton (B)
* This Singleton (A) must be fully constructed before the constructor of (B)
* is called.
*/
class MySingleton
{
private:
// Private Constructor
MySingleton();
// Stop the compiler generating methods of copy the object
MySingleton(MySingleton const& copy); // Not Implemented
MySingleton& operator=(MySingleton const& copy); // Not Implemented
public:
static MySingleton& getInstance()
{
// The only instance
// Guaranteed to be lazy initialized
// Guaranteed that it will be destroyed correctly
static MySingleton instance;
return instance;
}
};
OK. Lets get some criticism and other implementations together.
:-)