此处ObjectCache的由来:
实际使用过程中往往要讲xml数据解析成对象,这是一个非常消耗cpu的过程,所以引入cache机制,减少cpu的运算量,加快反应速度。是一种以空间换时间方法。
// CacheTimeoutException.cs
namespace Souline.LibCache
{
public class CacheTimeoutException : Exception
{
}
}
// CacheNotFoundException.cs
namespace Souline.LibCache
{
public class CacheNotFoundException : Exception
{
}
}
// ObjectCacheItem.cs
namespace Souline.LibCache
{
public class ObjectCacheItem<ObjectType>
{
private string m_Key;
private DateTime m_CacheTime;
private ObjectType m_Object;
public ObjectCacheItem(string A_Key, ObjectType A_Object)
{
this.m_Key = A_Key;
this.m_Object = A_Object;
this.m_CacheTime = DateTime.Now;
}
public string Key
{
get
{
return this.m_Key;
}
}
public DateTime CacheTime
{
get
{
return this.m_CacheTime;
}
}
public ObjectType Object
{
get
{
return this.m_Object;
}
set
{
this.m_CacheTime = DateTime.Now;
this.m_Object = value;
}
}
}
}
// ObjectCache.cs
using System.Collections.Generic;
namespace Souline.LibCache
{
public class ObjectCache<ObjectType>
{
private Dictionary<string, ObjectCacheItem<ObjectType>> m_Cache = new Dictionary<string, ObjectCacheItem<ObjectType>>();
private int m_Timeout;
public ObjectCache(int A_Timeout)
{
this.m_Timeout = A_Timeout;
}
public bool Cached(string strKey)
{
return this.m_Cache.ContainsKey(strKey);
}
public ObjectType GetItem(string strKey)
{
if(!this.Cached(strKey))
{
throw new CacheNotFoundException();
}
if(this.CacheTime.AddSeconds(this.m_Timeout) < DateTime.Now)
{
throw new CacheTimeoutException();
}
return this.m_Cache[strKey].Object;
}
public void Update(string strKey, ObjectType objItem)
{
ObjectCacheItem<ObjectType> objCacheItem = null;
if(!this.Cached(objItem))
{
objCachedItem = new ObjectCacheItem<ObjectType>(strKey, objItem);
this.m_Cache.Add(strKey, objCachedItem);
}
else
{
objCachedItem = this.m_Cache[strKey];
objCachedItem.Object = objItem;
}
}
}
}