Saturday, February 18, 2017

Singleton Design Pattern In C++

Singleton Design Pattern is used to keep one instance of a class in the system. To implement this pattern in C++, language features like access modifiers (public, protected, private), class functions and variables by using static, pointer and dynamic memory is used.

To keep single instance of particular class, developers must be prevented from creating new objects. In order to achieve that constructors of that particular class must be private. Doing so, new object of that class cannot be created. Object creating is facilitated well control manner to keep one instance of that class in the system by a public class method. The created single instance also is kept in the class variable. So when program request an instance, if that variable has the instance that instance is returned. Otherwise new instance is created and returned. All subsequent calls to object creation method returns the single instance that is kept in the class variable. 

Below implementation use static ThreadPool *getInstance() method to create or get single instance.

Implementation

#include <iostream>

using std::cout;
using std::endl;

class ThreadPool {
   private:
      static ThreadPool *tPSingleton;
      ThreadPool ();

   public:
      static ThreadPool *getInstance();
      bool startThreadPool();
      bool stopThreadPool();

      ~ThreadPool ();

};

ThreadPool* ThreadPool::tPSingleton = NULL;


ThreadPool::ThreadPool (){
   cout<<"Thread Pool is created"<<endl;
}

ThreadPool::~ThreadPool (){
   cout<<"Thread Pool is destroyed"<<endl;
}

ThreadPool *ThreadPool::getInstance(){
   if(ThreadPool::tPSingleton == NULL){
      ThreadPool::tPSingleton = new ThreadPool;
   }

   return ThreadPool::tPSingleton;
}

bool ThreadPool::startThreadPool(){
   cout<<"Thread pool is being started"<<endl;
   return true;
}

bool ThreadPool::stopThreadPool(){
   cout<<"Thread pool is being stoped"<<endl;
   return true;
}

int main() {
   ThreadPool *threadPool1;
   ThreadPool *threadPool2;
   
   /*
       threadPool1 = new ThreadPool;

       Produce below error with Error No 1
   */

   threadPool1 = ThreadPool::getInstance();
   threadPool1->startThreadPool();
   threadPool1->stopThreadPool();

   threadPool2 = ThreadPool::getInstance();
   threadPool2->startThreadPool();
   threadPool2->stopThreadPool();

   return 0;
}

/*

Error No 1

singleton.cpp: In function ‘int main()’:
singleton.cpp:23:1: error: ‘ThreadPool::ThreadPool()’ is private
 ThreadPool::ThreadPool (){
 ^
singleton.cpp:52:22: error: within this context
    threadPool1 = new ThreadPool;   
                      ^

*/

Output

Thread Pool is created
Thread pool is being started
Thread pool is being stoped
Thread pool is being started
Thread pool is being stoped

No comments:

Post a Comment