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.
// singleton.h
#ifndef __SINGLETON_H
#define __SINGLETON_H
template <class T>
class Singleton
{
public:
static T& Instance() {
static T _instance;
return _instance;
}
private:
Singleton(); // ctor hidden
~Singleton(); // dtor hidden
Singleton(Singleton const&); // copy ctor hidden
Singleton& operator=(Singleton const&); // assign op hidden
};
#endif
// eof
This implementation is so simple that I really love it. It implements the singleton behavior that we can add onto any class T we provide as the template parameter.
To transform the Log class from the beginning of the previous article to a singleton, without adding an Instance() function and hiding the constructor, destructor etc, I could define it this way:
typedef Singleton<Log> LOG;
And I can write to the log from any location in the application code (as long as it includes the necessary headers):
LOG::Instance().Write(“This is a logline”);
The great benefit of the above implementation is that we never have to change the singleton.h header file and can use it to transform any of our classes into a singleton -- without changing them!
Next: Testing Our Generic Implementation >>
More C++ Articles
More By J. Nakamura