使用场景:
● 要求生成唯一序列号的环境;
● 在整个项目中需要一个共享访问点或共享数据,例如一个Web页面上的计数器,可以不用把每次刷新都记录到数据库中,使用单例模式保持计数器的值,并确保是线程安全的;
● 创建一个对象需要消耗的资源过多,如要访问IO和数据库等资源;
● 需要定义大量的静态常量和静态方法(如工具类)的环境,可以采用单例模式(当然,也可以直接声明为static的方式)。
#pragma once
#include "stdafx.h"
class CSingletonEx
{
private:
CSingletonEx()
{
memset(szDevice, 0, 128);
strcpy_s(szDevice, "");
}
static CSingletonEx *pSingleton;
char szDevice[128];
public:
~CSingletonEx()
{
cout << "call destructor~~~" << endl;
}
static CSingletonEx* getInstance()
{
return pSingleton;
}
static void release()
{
if (pSingleton)
{
delete pSingleton;
pSingleton = NULL;
cout << "call release~~~" << endl;
}
}
void setDevice(const char *pStrDevice)
{
strcpy_s(szDevice, pStrDevice);
}
void printHelloDevice()
{
cout << "Hello," << szDevice << endl;
}
};
CSingletonEx* CSingletonEx::pSingleton = new CSingletonEx;
以上单例模式实现代码是线程安全的。
以下这种单例模式实现代码是非线程安全的。需加入锁,才能保证是线程安全的。
#pragma once
class CSingleton
{
private:
CSingleton()
{
}
static CSingleton *pSingleton;
public:
~CSingleton()
{
}
static CSingleton* getInstance()
{
if (pSingleton)
{
return pSingleton;
}
else
{
pSingleton = new CSingleton();
return pSingleton;
}
}
void printHelloUser(char *pStrName)
{
cout << "Hello," << pStrName << endl;
}
};
CSingleton* CSingleton::pSingleton = NULL;