最简单的Cache

using System;
using System.Collections.Generic;

namespace DomainBase
{
   
public class ObjectCache
    {
       
//Dictionary<K,T> 会自动维护一个空链表来保存不用的单元。
       
//这里,使用被缓存对象的“弱引用”,允许这些对象被垃圾回收。

       
private Dictionary<string, WeakReference> Buffer = new Dictionary<string, WeakReference>();

       
public object this[string key]
        {
           
get
            {
                WeakReference ret;
               
if (Buffer.TryGetValue(key, out ret) && ret.IsAlive)
                   
return ret.Target;
               
else
                   
return null;
            }
           
set
            {
                WeakReference ret;
               
if (Buffer.TryGetValue(key, out ret))
                    ret.Target
= value;
               
else
                    Buffer.Add(key,
new WeakReference(value));
            }
        }

       
public void Remove(string key)
        {
            Buffer.Remove(key);
        }
    }
}



这就是最简单的Cache。例如:

public Class User
{
    static ObjectCache Buffer=new ObjectCache();

    public static GetUser(string id)
    {
      User ret=Buffer[id];
      if(ret==null)
      {
            ret=读取数据库产生User对象(id);
            Buffer[id]=ret;
      }
      return ret;
    }
posted @ 2009-03-09 22:20  温景良(Jason)  Views(356)  Comments(2Edit  收藏  举报