Wednesday, April 21, 2010

Singelton Design pattern

Singleton design pattern in used in cases where you want to have only one instance of the class.
Below is a sample code in c++ which shows how to achieve this
--------------------------------------------------------
//Header file : mySingleton.h file
class mySingleton
{

public:
static mySingleton* getInstance();
void releaseInstance();
void myFunction_1();
void myFunction_2();
private:
mySingleton();
~mySingleton();

private: //member varibles
static mySingleton* mStaticInstance;
static int mRefCount;
};
--------------------------------------------------------
//Source File : mySingleton.cpp


//Initilize the sttatic varibles to 0
mySingleton* mySingleton::mStaticInstance = 0;
int mySingleton::mRefCount = 0;

mySingleton* mySingleton::getInstance()
{
if(!mySingleton::mStaticInstance)
{
mySingleton::mStaticInstance = new mySingleton();
}
// Increment the reference count
mySingleton::mRefCount++;
return mySingleton::mStaticInstance;

}
void mySingleton::releaseInstance()
{
if(mySingleton::mRefCount > 0)
{
//Decrease the reference count
mySingleton::mRefCount--;
}
// delete if referece count is zero
if (mRefCount== 0)
{
delete mStaticInstance;
mStaticInstance = NULL;
}


}
mySingleton::mySingleton()
{
//Private constructor, so that it cannot be instantiated
//Inilitize data memebers,if any , for the class

}

mySingleton::~mySingleton()
{

//release resouces, if any

}

void mySingleton::myFunction_1()
{
//perform your operation

}


void mySingleton::myFunction_2()
{
//perform your operation

}


--------------------------------------------------------
//main function

main ()
{

//Get the singleton instance
mySingleton* sPtr = mySingleton::getInstance();

//Perfrom operaions
sPtr->myFunction_1();
sPtr->myFunction_2();

//Release the instance
sPtr->releaseInstance();
}

No comments: