Tag Archives: Singleton Design Pattern

Singleton Class

28 Jan

A singleton class can have only one object.

To create singleton class we need to block normal way of creating class by blocking access to the constructor and provide a new function which will return only one instance of the object.

This function will also perform checking to see if there is only one instance of that object in existence.

The code flow below describe a way to create a Singleton class

Class Singleton {

protected:

// Stops creating any object via normal route

Singleton( );

public:

Singleton* instance( );

Singleton(const Singleton &); // Copy constructor

Singleton & operator= (const Singleton &); // Assignment operator

 

private:

static Singleton* instance_ptr;

};

 

// Implementation

Singleton* Singleton::instance_ptr = 0;

Singleton* Singleton::instance ( )

{

if ( *instance_ptr = = 0)

{

Instance_ptr = new Singleton;

return instance_ptr;

}

else

            return 0;

}