Monday, 15 June 2020

Singleton Design Pattern

In singleton design pattern, we restrict the instantiation of the object to only one. We make the constructor private and create a static method to control the instantiation
class Singleton {
Singleton() {};//make the constructor private
static Singleton* _obj;// private object so that access is restricted
public:
//method to create object
static Singleton*Getinstance() {
if (_obj == NULL)
_obj = new Singleton();
return _obj;
}
//method to delete the object
static void DeleteInstance()
{
if (_obj)
{
delete _obj;
_obj = NULL;
}
}
};
//initialize the object
Singleton* Singleton::_obj = NULL;
int main()
{
//usage
Singleton*pobj = Singleton::Getinstance();
Singleton::DeleteInstance();
return 0;
}
view raw Singleton.cpp hosted with ❤ by GitHub

No comments:

Post a Comment