Singleton
Singleton.h
#include <stdio.h>
#ifndef SINGLETON_H_
#define SINGLETON_H_
class Singleton {
public:
virtual ~Singleton();
static Singleton *getInstance();
long getNum();
void addNum(long newNum);
protected:
Singleton();
private:
static Singleton *mySingleton;
long myNum;
};
#endif /* SINGLETON_H_ */
Singleton.cpp
#include "Singleton.h"
Singleton *Singleton::mySingleton;
Singleton::Singleton() {
myNum = 0;
}
Singleton::~Singleton() {
if (mySingleton != NULL) {
delete mySingleton;
}
}
Singleton* Singleton::getInstance() {
if (mySingleton == NULL) {
mySingleton = new Singleton();
}
return mySingleton;
}
long Singleton::getNum() {
return myNum;
}
void Singleton::addNum(long newNum) {
myNum += newNum;
}
main
#include <iostream>
#include "Singleton.h"
using namespace std;
int main(int argc, char * argv[]) {
Singleton::getInstance()->addNum(5);
Singleton::getInstance()->addNum(3);
cout << Singleton::getInstance()->getNum() << endl;
return 1;
}