Singleton Pattern | Part 1

Lets start with definition of design pattern.

design pattern is a general reusable solution to a commonly occurring problem within a given context in software design.

Singleton Pattern comes under Creational Pattern.

In this part we will discuss its Intention, Motivation, Examples and its implementation.

So , What is intention to use Singleton Pattern?

  • To ensure a class only has one instance.
  • Provide a global point of access to it. 

When to use Singleton?

  • When we need to access a shared resource.
  • When we need to access the resource from multiple parts of the system.
  • When we need only one object.

Examples:

  • Printer Spooler

One question often arise that why not to use global variable instead of singleton pattern?

Because using global variable , Create object when application begins.

A global variable makes an object accessible, but does not keep you from instantiating multiple objects. So multiple object would create. Which is violating singleton pattern requirement.

Solution

A better solution is to make the class itself responsible for keeping track of its sole instance. The class ensures that no other instance can be created (by intercepting requests to create new objects) and it provides a way to access the instance.

Lets concentrate on Singleton pattern implementation in c++:

Few points to consider while implementing singleton class:

  • Default constructor should be private otherwise It is possible to create multiple instances!
  • Copy constructor and copy assignment operator should be private otherwise It would be possible to create multiple instances by copying! using below code:
Singleton  myCopy(*Singleton::getInstance());
  • Destructor should be private otherwise client can destruct this object and then create new object which is violating singleton requirement.

So Top level implementation look like this:

//C++ implementation
class  Singleton  {
public:
static  Singleton&  getInstance();

private:
Singleton();
Singleton(const  Singleton&);
Singleton&  operator=(const  Singleton&);  //  copyable
~Singleton();  //  indestructible static  Singleton*  instance_;
};

Implementation of getInstance() function


// from the implementation file
Singleton* Singleton::pInstance = 0;
Singleton* Singleton::getInstance()
{
    if (pInstance == 0) {
        pInstance = new Singleton;
    }
    return pInstance;
}

In next part we will cover its feasibility in multi threaded environment.

Site Footer