C++ Singleton

Singleton

  • Singleton is a creational design pattern.
  • A design pattern to provide one and only instance of an object.
  • Make the constructors of the class private.
  • Store the object created privately.
  • Provide access to get the instance through a public method.
  • Can be extended to create a pool of objects.

Sample Program

#include <iostream>using namespace std;// Singleton classclass MySingleton {public:static MySingleton* iInstance;public:static MySingleton* GetInstance();private:// private constructorMySingleton();};MySingleton* MySingleton::iInstance = NULL;MySingleton::MySingleton(){cout << "In construtor ..." << endl;}MySingleton* MySingleton::GetInstance(){if ( iInstance == NULL ) {iInstance = new MySingleton();}return iInstance;}void main(){MySingleton* obj;obj = MySingleton::GetInstance();}OUTPUT:In construtor ... (displayed only once)