Friday, June 8, 2007

Singleton Pattern

http://www.codeproject.com/cpp/singletonrvs.asp

The Singleton class is instantiated at the time of first access and same instance is used thereafter till the application quits. There is only one instance!

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.

using namespace std;

class Singleton
{
private:
static bool instanceFlag;
static Singleton *single;
Singleton()
{
//private constructor
}
public:
static Singleton* getInstance();
void method();
~Singleton()
{
instanceFlag = false;
}
};

bool Singleton::instanceFlag = false;
Singleton* Singleton::single = NULL;
Singleton* Singleton::getInstance()
{
if(! instanceFlag)
{
single = new Singleton();
instanceFlag = true;
return single;
}
else
{
return single;
}
}

void Singleton::method()
{
cout << "Method of the singleton class" << endl;
}

int main()
{
Singleton *sc1, *sc2;
sc1 =" Singleton::getInstance();
sc1->method();
sc2 = Singleton::getInstance();
sc2->method();

return 0;
}

No comments: