I have recently started working on a very old project and from the beginning of the project design pattern was not properly used. Now in one situation I want to make an already existing class a singleton class. In most tutorials I have seen that singleton classes uses a method to return object reference, like getInstance() in the following. Problem is everywhere in the project object is declared without help of any method except constructor. Is there any way to modify existing class so that without changing object creation method i can implement singleton pattern?
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;
}
Aucun commentaire:
Enregistrer un commentaire