Last active
February 11, 2017 01:37
-
-
Save huklee/89a6730c2b1a220c733a7145ec1194ca to your computer and use it in GitHub Desktop.
Design pattern : singleton, simple implementation in cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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