Skip to content

Instantly share code, notes, and snippets.

@lgp171188
Created August 13, 2014 08:12
Show Gist options
  • Save lgp171188/2923f11e2a34fa3d31df to your computer and use it in GitHub Desktop.
Save lgp171188/2923f11e2a34fa3d31df to your computer and use it in GitHub Desktop.
Singleton design pattern
#include<iostream>
using namespace std;
class Singleton
{
int x;
Singleton(int v):x(v){ }
Singleton(Singleton const&);
Singleton& operator=(Singleton const&);
public:
static Singleton& getInstance();
int getXValue();
void setXValue(int v);
};
Singleton& Singleton::getInstance()
{
static Singleton instance(12);
return instance;
}
int Singleton::getXValue()
{
return x;
}
void Singleton::setXValue(int v)
{
this->x = v;
}
int main()
{
Singleton& s = Singleton::getInstance();
cout<<Singleton::getInstance().getXValue()<<endl;
cout<<s.getXValue()<<endl;
cout<<&s<<endl;
Singleton::getInstance().setXValue(100);
cout<<Singleton::getInstance().getXValue()<<endl;
cout<<s.getXValue()<<endl;
cout<<&Singleton::getInstance()<<endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment