标签:style blog http io color os sp strong div
单例模式(Singleton)
保证一个类只有一个实例,并提供一个访问它的全局访问点。
关键在于要有
1、一个私有的构造函数
2、一个公有的析构函数
3、一个生成实例的接口
4、线程安全
Talk is cheap, show me the code.
#include <iostream>
using namespace std;
class CObj
{
private:
CObj() { cout << "Instance a object" << endl; }
public:
virtual ~CObj() {cout << "CObj::~CObj" << endl; if(! s_pObj) delete s_pObj; s_pObj = 0; }
static CObj* Instance()
{
//double lock
if(0 == s_pObj)
{
//thread synchronization begin
if(0 == s_pObj)
{
s_pObj = new CObj();
}
//thread synchronizatioin end
}
return s_pObj;
}
void Show() { cout << "CObj::Show()" << endl; }
protected:
static CObj* s_pObj;
};
CObj* CObj::s_pObj = 0;
int main()
{
CObj* pObj = CObj::Instance();
pObj->Show();
delete pObj;
pObj = 0;
return 0;
}
运行结果
标签:style blog http io color os sp strong div
原文地址:http://www.cnblogs.com/cuish/p/4093937.html