1.实现代码
代码如下:
#ifndef H_CACHEMGR
#define H_CACHEMGR
#include <ace/Hash_Map_Manager.h>
#include <algorithm>
#include <vector>
using namespace std;
template <class T> class CCachedItem {
public:
T obj_;
unsigned int use_count_; ///< 使用计数
public:
CCachedItem():obj_(0),use_count_(0) {
}
};
template <class T> int remove_out_cmp(pair<CCachedItem<T>*,int> p1,pair<CCachedItem<T>*,int> p2) {
return p1.second < p2.second;
}
template <class Key,class T> class CCacheMgr {
public:
unsigned int max_size_;
ACE_Hash_Map_Manager<Key,CCachedItem<T>*,ACE_Thread_Mutex> m_;
public:
CCacheMgr():max_size_(2048) {
}
int Get(Key key,T &o) {
CCachedItem<T>* wo = 0;
m_.find(key,wo);
if (wo) {
o = wo->obj_;
wo->use_count_++;
return 0;
}
return -1;
}
int Remove(Key key) {
CCachedItem<T>* wo=0;
m_.unbind(key,wo);
if (wo) {
wo->obj_->Release();
delete wo;
return 0;
}
return -1;
}
int RemoveOut(int n) {
ACE_Hash_Map_Manager<Key,CCachedItem<T>*,ACE_Thread_Mutex>::ENTRY *entry = 0;
ACE_Hash_Map_Manager<Key,CCachedItem<T>*,ACE_Thread_Mutex>::ITERATOR iter(m_);
vector<pair<CCachedItem<T>*,int> > v;
while(iter.next(entry)) {
CCachedItem<T>* o = entry->int_id_;
v.push_back(make_pair(o,o->use_count_));
iter.advance();
}
sort(v.begin(),v.end(),remove_out_cmp<T>);
for (int i=0;i<n;i++) {
CCachedItem<T> *wo = v[i].first;
Remove(wo->obj_->GetKeyValue());
}
return 0;
}
int Add(Key key,T o) {
if (m_.current_size()>max_size_) {
RemoveOut((max_size_+4)/5);
}
CCachedItem<T>* wo = new CCachedItem<T>;
wo->obj_ = o;
CCachedItem<T>* old_wo = 0;
m_.rebind(key,wo,old_wo);
if (old_wo) {
old_wo->obj_->Release();
delete old_wo;
}
return 0;
}
};
#endif
2.测试代码
#include "CacheMgr.h"
struct stData {
int n_;
stData(int n):n_(n) {
}
void Release() {
delete this;
}
int GetKeyValue() {
return n_;
}
};
int test() {
CCacheMgr<int,stData*> mgr;
mgr.max_size_ = 2;
mgr.Add(1,new stData(1));
mgr.Add(2,new stData(2));
stData *obj;
mgr.Get(1,obj);
mgr.Get(1,obj);
mgr.Get(2,obj);
mgr.Add(3,new stData(3));
mgr.Add(4,new stData(4));
obj = 0;
mgr.Get(3,obj);
return 0;
}
3.应用
class CMyGoodsMgr : public IMyGoodsMgr,public CRootObject {
CCacheMgr<ACE_CString,CMyGoods*> m_mapMyGoods;
};