Why?
Ensure a class only has one instance and provide a global point of access to it.
Code:
#include <iostream>
using namespace std;
class Singleton {
public:
static Singleton* getInstance();
protected:
Singleton();
private:
static Singleton* _instance;
};
Singleton* Singleton::_instance = 0;
Singleton::Singleton() {
cout << "Singleton::Singleton()" << endl;
}
Singleton* Singleton::getInstance() {
if (_instance == 0) {
_instance = new Singleton;
}
return _instance;
}
int main()
{
Singleton* singleton = Singleton::getInstance();
}
Sample run:
Singleton::Singleton()
No comments:
Post a Comment