Design Patterns

Singleton



Design Pattern Type: Creational

GoF Statement of Intent:


Ensure a class has only one instance, and provides a global point of access to it.
Brief Overview:



Make the constructor of a class a private member then create a static getInstance() function that returns a pointer to the one and only instance of the class.
UML Diagram:

Discussion and In-class Example:

This is perhaps the simplest of all the Design Patterns. The Single insures that there can be one and only one instance of an object. The implementation is quite simple. The constructor is made a private function (do not make the destructor private or there will be problems). The class includes a static function which maintains a static pointer to an instance of the class. When this function is called if the pointer is NULL then it instantiates the one and only allowable instance and returns the pointer. Any other calls the the function are returned the singleton pointer. The code below demonstrates the use of the Singleton Pattern.

//=================================
// SingletonDemo.h
//=================================
#ifndef SINGLETONDEMO_H
#define SINGLETONDEMO_H
class SingletonDemo
{
	private:
		int instanceNumber;
		SingletonDemo();
	public:
		~SingletonDemo();
		int getInstanceNumber();
		static SingletonDemo *getInstance();
};
#endif

//===============================
// SingletonDemo.cpp
//===============================
#include "SingletonDemo.h"
SingletonDemo::SingletonDemo()  {}
SingletonDemo::~SingletonDemo()  {}

//===============================
// Return the instance number.
// This will always be 1
//===============================
int SingletonDemo::getInstanceNumber()
{
    return this->instanceNumber;
}

//===============================
// Return the singleton instance
//===============================
SingletonDemo *SingletonDemo::getInstance()
{
    static SingletonDemo *theInstance = NULL;
    static int counter = 1; 
    if(theInstance == NULL)
    {
        theInstance = new SingletonDemo();
        theInstance->instanceNumber = counter;
        counter++; 
    }
    return theInstance;
}