Monday, August 14, 2006

Singleton Pattern

Its intent is to ensure that a class only has one instance, and provide a global point of access to it. by using a private constructor and a static method to create and return an instance of the class is a popular way for implementing Singleton Pattern

class Singleton
{
private:
static bool instanceFlag;
static Singleton *single;
Singleton()
{
//private constructor
}
public:
static Singleton* getInstance()
{
if(! instanceFlag)
{
single = new Singleton();
instanceFlag = true;
return single;
}
else
{
return single;
}
}

void method()
{
cout << "Method of the singleton class" << endl;
};
~Singleton();
};
bool Singleton::instanceFlag = false;
Singleton* Singleton::single = NULL;Singleton *sc1,*sc2;
sc1 = Singleton::getInstance();
sc1->method();
sc2 = Singleton::getInstance();
sc2->method();



double check the GOF book

No comments:

Post a Comment