Sunday, October 14, 2012

Singleton design pattern in C++


#include<iostream>
using namespace std;

class Singleton{
private:
Singleton(){}
static Singleton* obj;
int x;
public:
static Singleton* getInstance(){
if(obj==NULL){
cout<<"constructing object"<<endl;
obj = new Singleton();
}
return obj;
}
void setdata(int);
void display();

};

void Singleton::setdata(int x){
this->x = x;
}

void Singleton::display(){
cout<<this->x<<endl;
}

Singleton* Singleton::obj = NULL;

int main(){
Singleton *s1 = Singleton::getInstance();
Singleton *s2 = Singleton::getInstance();
s1->setdata(5);
s1->display();
s2->display();
return 0;
}

No comments:

Post a Comment