工作中一些类对象在整个工程中只需要有一份就可以,例如:线程池、内存池、日志引擎、数据库引擎等等。我们可以处理的方法有:定义成全局变量、使用单实体模式(自己取的名称)。下面实例时用到了2个方法:Singleton和SingletonEx。
直接看代码
#pragma once
#include <assert.h>
#include "Lock.h"
template<class T, bool mustDelete = true>
class Singleton
{
static T* _instance;
static Mutex _mu;
public:
static T& getInstance()
{
if (!_instance)
{
ResGuard<Mutex> lock(_mu);
if (!_instance)
{
_instance = new T;
if (mustDelete) atexit(releaseInstance);
}
}
return *_instance;
}
protected:
Singleton() { }
static void __cdecl releaseInstance()
{
if (_instance && mustDelete)
{
delete _instance;
_instance = 0;
}
}
};
template <class T, bool mustDelete> T* Singleton<T, mustDelete>::_instance = NULL;
template <class T, bool mustDelete> Mutex Singleton<T, mustDelete>::_mu;
template <typename T>
class SingletonEx
{
protected:
static T* _instance;
public:
SingletonEx()
{
assert(!_instance);
_instance = static_cast<T*>(this);
}
~SingletonEx()
{
assert(_instance);
_instance = 0;
}
static T& getInstance() { assert(_instance); return (*_instance); }
static T* getInstancePtr() { return _instance; }
};
template <typename T> T* SingletonEx<T>::_instance = 0;
#endif