单例模式
饿汉式与懒汉式代码
class singleTon
{
private:
singleTon() {}
~singleTon() {}
public:
static singleTon* getInstance() {
if(NULL == instance_ ) // 多线程的情况下需要加锁
instance_ = new singleTon();
return instance_;
}
private:
//用于自动回收
class garbo
{
public:
~garbo() {
if (instance_ != NULL) {
delete instance_;
}
}
};
private:
static singleTon* instance_;
static garbo garbo_;
};
#ifndef LAZY_MODE // 没有定义懒汉式初始化
singleTon* singleTon::instance_ = new singleTon();
#endif // !LAZY_MODE
singleTon::garbo singleTon::garbo_;
void test_singleTon(){
singleTon::getInstance();
}