56 lines
1.5 KiB
C++
56 lines
1.5 KiB
C++
#ifndef SINGLETONBASE_H
|
|
#define SINGLETONBASE_H
|
|
|
|
//做一个单例
|
|
#include <QHash>
|
|
|
|
template<typename KeyType,typename ValueType,typename ChildType>
|
|
class SingletonBase
|
|
{
|
|
public:
|
|
// SingletonBase();
|
|
// ~SingletonBase();
|
|
void add(const KeyType& key,const ValueType& val)
|
|
{
|
|
QHash<KeyType,ValueType> *t=SingletonBase<KeyType,ValueType,ChildType>::ht;
|
|
(*t)[key]=val;
|
|
}
|
|
bool contains(const KeyType& key)
|
|
{
|
|
return SingletonBase<KeyType,ValueType,ChildType>::ht->contains(key);
|
|
}
|
|
ValueType get(const KeyType& key)
|
|
{
|
|
QHash<KeyType,ValueType> *t=SingletonBase<KeyType,ValueType,ChildType>::ht;
|
|
return (*t)[key];
|
|
}
|
|
void initInstance()
|
|
{
|
|
if(SingletonBase<KeyType,ValueType,ChildType>::ht)
|
|
{
|
|
delete SingletonBase<KeyType,ValueType,ChildType>::ht;
|
|
SingletonBase<KeyType,ValueType,ChildType>::ht==NULL;
|
|
}
|
|
SingletonBase<KeyType,ValueType,ChildType>::ht=new QHash<KeyType,ValueType>;
|
|
}
|
|
protected:
|
|
|
|
class CG // 它的唯一工作就是在析构函数中删除CSingleton的实例
|
|
{
|
|
public:
|
|
~CG()
|
|
{
|
|
if (SingletonBase::ht)
|
|
delete SingletonBase::ht;
|
|
}
|
|
};
|
|
static CG Garbo; // 定义一个静态成员,在程序结束时,系统会调用它的析构函数
|
|
static QHash<KeyType,ValueType> *ht;
|
|
};
|
|
|
|
|
|
template<typename KT,typename VT,typename CT>
|
|
QHash<KT,VT> *SingletonBase<KT,VT,CT>::ht=NULL;
|
|
|
|
#endif // SINGLETONBASE_H
|