- 保证在应用程序中,一个类只有一个对象
- 将构造函数设置为私有,在类的实现中确保生成对象的个数
class Singleton{
public:
static Singleton* getInstance();
void doSomething();
void destroy();
private:
Singleton();
~Singleton();
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
static Singleton* instance;
};
Singleton* Singleton::instance = NULL;
void Singleton::doSomething(){
cout << "do something" << endl;
}
void Singleton::destroy(){
delete this;
instance = NULL;
}
Singleton::Singleton(){
cout << "singleton created" << endl;
}
Singleton::~Singleton(){
cout << "singleton destroyed" << endl;
}
Singleton* Singleton::getInstance(){
Singleton* ret = instance;
if (instance == NULL){
instance = new Singleton();
ret = instance;
}
return ret;
}
int main()
{
Singleton* p = Singleton::getInstance();
p->doSomething();
p->destroy();
system("pause");
return 0;
}