The singleton design pattern is a Creational  design pattern which ensures a class has only one instance and provides a global point of access to that instance. A simple UML class diagram for singleton class is shown below.

Singleton design pattern

The simple and lazy initialization of singleton class example c++ code is below.

#include<iostream>
using namespace std;

class Singleton
{
   public:
      static Singleton *GetInstance (void)
      {
         if (instance == 0)
         // Critical segment.
         instance = new Singleton;
         return instance;
       }

      void othermethod (void)
      {
         cout << "hello singleton" << endl;
      };

   private:
      Singleton (){};

   Singleton (Singleton const &);	//need no implementation 
   void operator= (Singleton const &);	// need no implementation
   static Singleton *instance;
};

  //initializing Singleton class static data member. 
  Singleton *
  Singleton::instance = 0;

int main ()
{
     // how to use 
     Singleton::GetInstance ()->othermethod ();
     return 0;
}

Note: The above implementation is good in case of single threaded environment or single threaded application. But it is not reliable in multi threaded application. Even in case of single threaded environment or application, an interrupt can be problematic.

 How classic singleton design pattern is problematic for multi threaded application?

Singleton design pattern

From the above figure it is clear that there are two objects even class is singleton.

what is solution of above problem?

  • Synchronizing the critical section is solution.
  • Look at the above code , the critical section is the section where new instance is getting called (line no 11).
  • Double check locking design pattern is a solution which make the singleton thread safe. Read next link to know more about “Double check locking


Related Contents to follow