Thursday, March 24, 2011

Singleton Pattern

definition:

The singleton Pattern ensures a class has only one instance, and provides a global point of access to it


public class Singleton {
private static Singleton uniqueInstance;
// other useful instance variables here
private Singleton() {}
public static Synchronized Singleton getInstance() { if (uniqueInstance == null) {
synchronized
uniqueInstance = new Singleton(); return uniqueInstance;
}


But , synchronized is expensive.
the only time synchronization is relevant is the first time through this method. In other words, once we've set the uniqueInstance variable to an instance of Singleton, we have no further need to synchronize this method. After the first time through, synchronization is totally unneeded overhead!





/*
Creational Pattern: SINGLETON
Author: Rajesh V.S
Language: C++
Email: rajeshvs@msn.com
*/

#include


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;
}







For other c++ singleton pattern code: check here:
http://www.yolinux.com/TUTORIALS/C++Singleton.html

No comments:

Post a Comment