Sunday, May 18, 2008

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 class
class MySingleton {

    public:
        static MySingleton* iInstance;

    public:
        static MySingleton* GetInstance();

    private:
        // private constructor
        MySingleton();

};

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)

Contact Form

Name

Email *

Message *

Back to Top