如下内容是学习《Head First 设计模式》第五部分《单件模式》所得,主要就是一些原文摘抄和少量自己的总结。
单件模式确保类只有一个实例,并提供一个全局访问点。
这个 Solution 的 SingletonPattern 工程里。
Visio 原图见这里:
class CSingleton
{
public:
static CSingleton* GetInstance();
/**
释放单例,应仅限于所有对单例对象的使用完成后调用
*/
static void ReleaseInstance();
void DoSomething();
private:
CSingleton();
CSingleton(const CSingleton&); // private and not implemented copy constructor
CSingleton& operator=(const CSingleton&); // private and not implemented = operator
volatile static CSingleton* m_sUniqueInstance;
static HANDLE m_hSync;
};
volatile CSingleton* CSingleton::m_sUniqueInstance = NULL;
HANDLE CSingleton::m_hSync = ::CreateEvent(NULL, FALSE, TRUE, NULL);
CSingleton* CSingleton::GetInstance()
{
if (NULL == m_sUniqueInstance)
{
WaitForSingleObject(m_hSync, INFINITE);
if (NULL == m_sUniqueInstance)
{
m_sUniqueInstance = new CSingleton();
}
SetEvent(m_hSync);
}
return (CSingleton*)m_sUniqueInstance;
}
void CSingleton::ReleaseInstance()
{
if (0 != m_sUniqueInstance)
{
delete m_sUniqueInstance;
m_sUniqueInstance = NULL;
}
if (NULL != m_hSync)
{
CloseHandle(m_hSync);
}
}
CSingleton ObjA(*CSingleton::GetInstance())
和CSingleton ObjB = *CSingleton::GetInstance())
的写法来得到第二、第三甚至更多的实例对象。扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有