:: printable version ::

The singleton design pattern

There are many circumstances where we need a way to globally access data without having to pass pointers almost everywhere. The singleton pattern provides a global access point to some class and it can ensure that only one instance (or some other fixed number of instances) exists in the whole application. As an example, you may want to access a class or structure holding application-wide preferences from within various classes. A classic solution is to have constructors taking a pointer to that class. A cleaner solution involves a singleton class.

Althought there may be different ways to implement a singleton class, here is a simple C++ example. It ensures only one instance of our singleton class is created. Both class declaration and implementation are quite self-explanatory.

// *** mysingleton.h ***
class mySingleton { public: static mySingleton* getInstance();
// this is our global access point
virtual ~mySingleton();
// our nice destructor
// other class-specific public functions or variables
private: mySingleton();
// private constructor
mySingleton* instance;
// unique application wide instance
// other class-specific private functions or variables

The class implementation would look like this:

// *** mysingleton.cpp ***
#include "mysingleton.h" mySingleton* mySingleton::instance = 0;
// initialize our static pointer
mySingleton* mySingleton::getInstance() { if (instance == 0) instance = new mySingleton(); return instance; }
// this is our private constructor
mySingleton::mySingleton() {
// do whatever the constructor of this class needs to do
// the destructor should do some checks
mySingleton::~mySingleton() { if (this == instance) { instance = 0; } }

Looking at the example code, you will see that there are only two unusual things: a pointer to a static instance of our singleton class (this ensures we only have one application-wide instance) and a private constructor (this ensures users cannot instantiate the class directly). Using a static pointer in place of a static object to handle the global instance makes our class more robust, as some compilers fail to call the constructor for static objects, especially in libraries.

Again, this is just a simple example. The pattern can be adapted and extended to best fit to your needs.

If you want to learn more about design patterns, you HAVE to read "Design Patterns" by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides (Addison-Wesley Professional, 1995).

There is a nice article featuring the singleton pattern in the tenth issue of Trolltech's Qt Quarterly newsletter.

:: index :: top ::