设计模式之单例模式

来源:互联网 发布:淘宝客独家是什么意思 编辑:程序博客网 时间:2024/05/19 16:33

// 单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点;


class Singelton
{
public:
static Singelton* GetInstance()
{
if (m_Instance == NULL)
{
m_Instance = new Singelton();
}
return m_Instance;
}
static Singelton *m_Instance;
double m_dTest;
private:
class GC // 垃圾回收类
{
public:
GC()
{
if (m_Instance == NULL)
{
m_Instance = new Singelton();
m_Instance->m_dTest = 1;
}
}
~GC()
{
cout<<"GC destruction"<<endl;
// We can destory all the resouce here, eg:db connector, file handle and so on
if (m_Instance != NULL)
{
delete m_Instance;
m_Instance = NULL;
cout<<"Singleton destruction"<<endl;
system("pause");//不暂停程序会自动退出,看不清输出信息
}
}
};

static GC gc;  //垃圾回收类的静态成员
};
// 客户端代码
#include "Singelton.h"
 Singelton* Singelton::m_Instance = NULL; // 注意静态变量类外初始化
 Singelton::GC Singelton::gc; 

// 保证一个类只有一个实例,并且提供一个访问它的全局访问点;
int _tmain(int argc, _TCHAR* argv[])
{
Singelton* s1 = Singelton::GetInstance();
Singelton* s2 = Singelton::GetInstance();
s1->Test();
s1->m_dTest = 1;

if(s1 == s2)
cout<<"ok"<<endl;
else
cout<<"no"<<endl;

return 0;
}

0 0
原创粉丝点击