Singleton Design Pattern example in C++

//Singleton is a creational design pattern.
//A design pattern to provide one and only instance of an object.
//Declare the constructors of the class private.
//Declatre a static public instance of class type.
//Provide a static public method to get the instance
//If instance is NULL then only once create a object else
//return the already created instance
#include<stdio.h>
using namespace std;
class singleton
{
private:
singleton(){printf("Constructor called only once.\n");}
public:
static singleton* instance;
static singleton* getinstance();
};
singleton* singleton::instance=NULL;

singleton* singleton::getinstance()
{
if(instance==NULL)
{
instance = new singleton;//mind the syntax//no singleston s;
}
else
{
return instance;
}
}
int main()
{
//singleton s1;//singleton() is private within this context
singleton *sptr;
sptr=singleton::getinstance();
sptr=singleton::getinstance();
sptr=singleton::getinstance();
sptr=singleton::getinstance();
sptr=singleton::getinstance();
return 0;
}
/*
Constructor called only once.
*/

Observer Design Pattern example in C++


No comments:

Post a Comment