Singleton模式就是单例模式:
在一个系统中要求一个类只能有一个实例使用单例模式。
特点上:
1. 单例类只能有一个实例
2. 单例类必须自己创建自己的唯一实例
3. 单一类必须给所有其他对象提供这一实例
单例模式的应用:
1. 每台计算机可以有若干个打印机,但只能有一个Printer Spooler,避免两个打印作业同时输出到打印机
2. 一个具有自动编号主键的表可以有多个用户同时使用,但数据库中只能有一个地方分配下一个主键编号,否则会出现主键重复。
代码如下:
Singleton.h文件
class CSingleton
{
public:
static CSingleton* GetInstance();
static void ReleaseInstance();
private:
CSingleton(void);
~CSingleton(void);
CSingleton(const CSingleton& rhs);
CSingleton& operator= (const CSingleton& rhs);
private:
static CSingleton* m_pInstance;
};
Singleton.cpp文件
#include "Singleton.h"
CSingleton* CSingleton::m_pInstance = NULL;
CSingleton::CSingleton(void)
{
}
CSingleton::~CSingleton(void)
{
}
CSingleton* CSingleton::GetInstance()
{
if (m_pInstance == NULL)
{
printf("Singleton:即将被实例化. \n");
m_pInstance = new CSingleton();
return m_pInstance;
}
else
{
printf("Singleton:已经被实例化. \n");
return m_pInstance;
}
}
void CSingleton::ReleaseInstance()
{
delete m_pInstance;
m_pInstance = NULL;
}
代码解释:该类只能调用静态成员函数GetInstance()和ReleaseInstance()来分配和释放资源,不能进行对象的复制和拷贝操作操作。