设计模式之单例模式

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


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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值