在架构设计时,某些类在整个系统生命期中最多只能有一个对象存在(Single Instance)
如何定义一个类,使得这个类最多只创建一个对象?
思路
- 要控制类的对象数目,必需对外隐藏构造函数
- 将构造函数的访问属性设置为 private
- 定义 instance 并初始化为 NULL
- 当需要使用对象时,访问 instance 的值
- 空值:创建对象,并用 instance 标记
- 非空值: 返回 instance 标记的对象
class CSingleton
{
static CSingleton *m_instance;
CSingleton(const CSingleton&);
CSingleton& operator = (const CSingleton&);
CSingleton()
{}
public:
static CSingleton* getInstance();
void print()
{
cout << "this = " << this << endl;
}
};
CSingleton* CSingleton::m_instance = NULL;
CSingleton* CSingleton::getInstance()
{
if( m_instance == NULL )
{
m_instance = new CSingleton();
}
return m_instance;
}
int main()
{
CSingleton* s = CSingleton::getInstance();
CSingleton* s1 = CSingleton::getInstance();
CSingleton* s2 = CSingleton::getInstance();
s->print();
s1->print();
s2->print();
return 0;
}
this = 0x1d1ec20
this = 0x1d1ec20
this = 0x1d1ec20
存在的问题
- 需要使用单例模式时:
- 必须定义静态成员变量 m_instance
- 必须定义静态成员函数 getInstance()
解决方案
将单例模式相关的代码抽取出来,开发单例类模板,当需要的单例类的时候
直接使用单例类模板
#ifndef _SINGLETON_H_
#define _SINGLETON_H_
template
< typename T >
class Singleton
{
static T* c_instance;
public:
static T* GetInstance();
};
template
< typename T >
T* Singleton<T>::c_instance = NULL;
template
< typename T >
T* Singleton<T>::GetInstance()
{
if( c_instance == NULL )
{
c_instance = new T();
}
return c_instance;
}
#endif
小结
- 单例模式是开发中最常用的设计模式之一
- 单例模式的应用使得一个类最多只有一个对象
- 可以将单例模式相关的代码抽象成类模板