Thinking in C++ Vol 2 - Practical Programming |
Prev |
Home |
Next |
Possibly the simplest GoF design pattern is the Singleton, which is a way to allow one and only one instance of a class. The
following program shows how to implement a Singleton in C++:
//: C10:SingletonPattern.cpp
#include <iostream>
using namespace std;
class Singleton {
static Singleton s;
int i;
Singleton(int x) : i(x) { }
Singleton&
operator=(Singleton&); // Disallowed
Singleton(const Singleton&); // Disallowed
public:
static Singleton& instance() { return s; }
int getValue() { return i; }
void setValue(int x) { i = x; }
};
Singleton Singleton::s(47);
int main() {
Singleton& s = Singleton::instance();
cout << s.getValue() << endl;
Singleton& s2 = Singleton::instance();
s2.setValue(9);
cout << s.getValue() << endl;
} ///:~
The key to creating a Singleton is to prevent the client
programmer from having any control over the lifetime of the object. To do this,
declare all constructors private, and prevent the compiler from
implicitly generating any constructors. Note that the copy constructor and assignment operator (which intentionally have no implementations, since they
will never be called) are declared private to prevent any sort of copies being
made.
You must also decide how you re going to create the object.
Here, it s created statically, but you can also wait until the client
programmer asks for one and create it on demand. This is called lazy initialization, and it only makes sense if it is expensive to create your object,
and if you don t always need it.
If you return a pointer instead of a reference, the user
could inadvertently delete the pointer, so the implementation above is
considered safest (the destructor can also be declared private or protected to
alleviate that problem). In any case, the object should be stored privately.
You provide access through public member functions. Here, instance( )
produces a reference to the Singleton object. The rest of the interface
(getValue( ) and setValue( )) is the regular class
interface.
Note that you aren t restricted to creating only one object.
This technique also supports the creation of a limited pool of objects. In that
case, however, you can be confronted with the problem of sharing objects in the
pool. If this is an issue, you can create a solution involving a check-out and
check-in of the shared objects.
Thinking in C++ Vol 2 - Practical Programming |
Prev |
Home |
Next |