Skip to content

Instantly share code, notes, and snippets.

@huklee
Last active February 11, 2017 01:37
Show Gist options
  • Save huklee/89a6730c2b1a220c733a7145ec1194ca to your computer and use it in GitHub Desktop.
Save huklee/89a6730c2b1a220c733a7145ec1194ca to your computer and use it in GitHub Desktop.
Design pattern : singleton, simple implementation in cpp
#include <iostream>
using namespace std;
class Singleton{
private:
static Singleton *u_instance;
int value;
Singleton(int val) : value(val) {};
~Singleton(){};
public:
int get_value()
{
return value;
}
void set_value(int val)
{
this->value = val;
}
static Singleton *get_instance()
{
if (!u_instance)
u_instance = new Singleton(0);
return u_instance;
}
};
// Allocation and initialization of the static data member
Singleton *Singleton::u_instance = 0;
int main(){
cout << "singleton value : ";
cout << Singleton::get_instance()->get_value() << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment