我们在工作中往往会用到单件类。但是我们知道单件类的实现就那么几步,如果系统中有多个单件类的话,去一个个写非常麻烦,那么怎么办呢?
单件模版类就派上用场了:
template <typename _CoClass>
class Singleton
{
public:
Singleton() {}
virtual ~Singleton() {}
static _CoClass& GetInstance()
{
if (!m_psInstance)
{
m_psInstance = new _CoClass();
}
return *m_psInstance;
}
private:
// 防止单件复制.
Singleton(const Singleton& copy);
Singleton& operator = (const Singleton& rhs);
static _CoClass* m_psInstance;
};
//
// 单件实例指针初始化.
//
template <typename _CoClass>
_Coclass* Singleton<_CoClass>::m_psInstance = 0;
那么该怎么用呢?如下: