程序中有时候需要保存全局的数据,比如程序的配置文件,需要随时检索的.比如程序中有些变量需要全局保存全局用,这时候我们不想用一个全局变量来保存
这时候,可以使用单例模式,从名称可以看出,单例模式就是类的实例全局只创建一个.怎么样才能保存只创建一个实例呢?
我们可以设置标识位,创建过的就不再创建了.下面是单例的简单实现
template<class T>
class Singleton
{
public:
static T* GetInstance()
{
static Mutex mutex;
if(!ms_instance)
{
Locker locker(mutex);
if (!ms_instance)
{
ms_instance = new T;
}
}
return ms_instance;
}
static void SetInstance(T* pInst)
{
ms_instance = pInst;
}
static void DeleteInstance()
{
if (ms_instance)
{
delete ms_instance;
ms_instance = NULL;
}
}
private:
class Garbo
{
public:
~Garbo()
{
if( Singleton::ms_instance )
{
delete ms_instance;
ms_instance = NULL;
}
}
};
static Garbo garbo;
protected:
Singleton() {}
~Singleton() {}
Singleton(const Singleton&) {}
Singleton& operator=(const Singleton&) {}
private:
static T* ms_instance;
};
template<class T>
T* Singleton<T>::ms_instance = 0;
用法:
class Test : public Singleton<Test>
{
//your code
}
Test::GetInstance()->your method