C++ In Theory: The Singleton Pattern, Part 2 - Singleton Generalization (Page 2 of 4 )
One of the rules I try to live up to, is that every function and every class should have a single purpose and responsibility. Bolting the Instance() function onto any class you would like to behave as a singleton (and hiding its constructor, destructor, copy constructor and assignment operator) is pretty intrusive and adds additional purpose and responsibility to the interface of that class. You might as well end up with two different versions of the same class: one normal and one singleton version. Would it not be nice to have a singleton class that could add this behavior to any of our classes, whenever we desire it, without having to make any changes?
An object-oriented programmer might be tempted to use class inheritance to solve this problem. After all, if our class is a singleton, should it not be derived from a singleton class?
It is very tricky to get Instance() to create the correct derived object without moving the functionality down into the derived class, and we would still force any derived class to hide the constructor, destructor and assignment operator as well. Defining a separate singleton baseclass becomes a bit superfluous (additional purpose and responsibility will still end up in the derived class), except that it enforces a certain standard to be followed. Additionally you most probably will have to use multiple inheritance to get your implementation right and will probably have multiple headaches (feel free to mail me if you would like me to write about the downsides and upsides of multiple inheritance; diamonds and extension interfaces are great fun!).
Enough threats made… let's look at the solution first.