Skip to content

Instantly share code, notes, and snippets.

@scriptpapi
Created May 24, 2018 21:29
Show Gist options
  • Save scriptpapi/f1c98943d4f6840c8af05f1608cafbf7 to your computer and use it in GitHub Desktop.
Save scriptpapi/f1c98943d4f6840c8af05f1608cafbf7 to your computer and use it in GitHub Desktop.
Singleton design pattern template
// A Template for implementing singleton design pattern.
class Singleton
{
public:
int getX(){ return var_x;}
int getY(){ return var_y;}
void setX(int x){ var_x = x;}
void setY(int y){ var_y = y;}
static Singleton *instance(){
if(!i_instance)
i_instance = new Singleton;
return i_instance;
}
private:
int var_x;
int var_y;
static Singleton *i_instance;
Singleton(){}
};
void foo(int yi){
Singleton::instance()->setY(yi);
cout << "global y value ptr is" << Singleton::instance()->getY() << endl;
}
void bar(int xi){
Singleton::instance()->setX(xi);
cout << "global x value ptr is" << Singleton::instance()->getX() << endl;
}
int main(){
cout << "global x value ptr is" << Singleton::instance()->getX() << endl;
Singleton::instance()->setX(5);
cout << "global x value ptr is" << Singleton::instance()->getX() << endl;
foo(-23);
bar(20);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment