Singleton Design Pattern Explained With Simple Example: Creational Design Pattern Category

The singleton design pattern ensures that at any point of time a class has one and only one instance which can be accessed globally. This design pattern is useful in cases where exactly one instance is needed to co-ordinate between different modules of a software. Singleton design pattern can be used as a logger class or memory/thread pool classes for which only one instance of object is needed. For Design patterns basic explanation see (Design Patterns Simplified Version)

Some important points:
1) All the constructors including copy constructors must be defined as protected or private to ensure it can’t be called from outside member function.
2) It must have a static attribute which is used to initialized the first object and return the same object if it’s already created.
3) It must have a static public accessor function which will return the pointer of the global object.
4) Assignment operator must be disallowed.

Singleton Design Pattern Example:

Let’s have a look on the singleton class example.

class Singleton
{
private:
	int m_data;
	string m_name;
	static Singleton* m_singleton;

	Singleton()
	{
		/* Private constructor to ensure nobody from outside can call it */
	}
public:
	void setValues(int data, string name)
	{
		m_data = data;
		m_name = name;
	}
	void printValues()
	{
		cout<<"Singleton class data value "<<m_data<<" and name "<<m_name<<endl;
	}
	~Singleton()
	{
		cout << "In Destructor" << endl;
	}
	static Singleton* Instance();
    void operator=(Singleton const&); //Don't implement
	Singleton(Singleton const&); //Don't implement
};

Singleton* Singleton::m_singleton = NULL;
Singleton* Singleton::Instance()
{
	if(!m_singleton)
		m_singleton = new Singleton();

	return m_singleton;
}

Let’s have a look on the sample main program which creates and uses this singleton class object. At the end of program execution global object is deleted.

int main()
{
	Singleton* singleton = Singleton::Instance();
	singleton->setValues(4,"Instance1");
	singleton->printValues();
	delete singleton; //This delete should be called when the program is exiting.
}

Let’s have a look on to output of this example.

Singleton class data value 4 and name Instance1
In Destructor

Leave a Reply

Your email address will not be published. Required fields are marked *