public abstract class BaseCache<Tkey,Tvalue> :CachesInterface<Tkey, Tvalue>
{
private Dictionary<Tkey, Tvalue> _innerStore;
protected Dictionary<Tkey, Tvalue> DataStore {
get { if (_innerStore == null)
return _innerStore = new Dictionary<Tkey, Tvalue>();
return _innerStore;
}
}
public bool CacheEnable { get; set; }
protected BaseCache()
{
CacheEnable = true;//暂时默认位true
_innerStore = new Dictionary<Tkey,Tvalue>();
}
public Tvalue GetCache(Tkey key) {
Tvalue value = default(Tvalue);
if (CacheEnable && DataStore.TryGetValue(key, out value))
{
return value;
}
else
{
value = CreateInstance(key);
DataStore[key] = value;
return value;
}
}
protected abstract Tvalue CreateInstance(Tkey type);
}
从这个抽象类继承重写CreateInstance,单例的完成在子类中
public sealed class ViewCaches :BaseCache<string,ViewMessage>
{
private volatile static ViewCaches instance = null;
public static ViewCaches Instance
{
get
{
return instance;
}
}
static ViewCaches()
{
instance = new ViewCaches();
}
private ViewCaches() :base() { }
protected override ViewMessage CreateInstance(string type)
{
ViewMessage viewMessage = new LOS.ViewMessage(type);
return viewMessage;
}
}
实例字段和构造完成里对象的全局唯一性,重写CreateInstance用于在找不到value的时候处理出需要的数据放回DataStore。