单例模式(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;
}
运行结果
---------------------------------华丽的分割线-----------------------------------------------------------
另一种单例模式的写法
1
2 #include <iostream>
3 using namespace std;
4
5 class CSingleton
6 {
7 public:
8 static CSingleton& Instance()
9 {
10 static CSingleton singleton;
11 return singleton;
12 }
13
14 virtual ~CSingleton() { cout << endl << "CSingleton::~CSingletion" << endl; }
15 void Show() { cout << endl << "This is CSingleton::Show() " << endl; }
16
17 protected:
18 CSingleton() { cout << endl << "CSingleton::CSingleton" << endl; }
19
20 };
21
22 int main()
23 {
24 CSingleton& singleton = CSingleton::Instance();
25 singleton.Show();
26
27 CSingleton& singleton2 = CSingleton::Instance();
28 singleton.Show();
29
30 return 0;
31 }
执行结果