欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

asp.net SAF 中緩存服務(wù)的實(shí)現(xiàn)第2/5頁(yè)

 更新時(shí)間:2008年08月08日 21:28:49   作者:  
對(duì)緩存的興趣源于張子陽(yáng)寫的一篇文章《SAF 中緩存服務(wù)的實(shí)現(xiàn)》中的一個(gè)例子:

類型接口 
我們先看一下類型的組織,然后再看實(shí)現(xiàn)。 

       ICacheStrategy用于定義如何添加、獲取、刪除欲進(jìn)行緩存的對(duì)象。實(shí)際上,在接口的實(shí)體類中要明確使用何種類型來(lái)存儲(chǔ)對(duì)象,是Dictionary還是Hashtable或者其他。 
C# 
復(fù)制代碼 代碼如下:

public interface ICacheStrategy {        
    void AddItem(string key, object obj);// 添加對(duì)象     
    object GetItem(string key);      // 獲取對(duì)象     
    void RemoveItem(string key); // 刪除對(duì)象     
}   
 
       接下來(lái)是Cache類,這個(gè)類包含了主要的邏輯,包括 動(dòng)態(tài)構(gòu)建的XML文檔、將Xml文檔映射到Hashtable 等。
復(fù)制代碼 代碼如下:

public class Cache {     
    void AddItem(string xpath, object obj);     
    object GetItem(string xpath);     
    object[] GetList(string xpath);     
    void RemoveItem(string xpath);     
}  
  
       僅從接口上看,這個(gè)類似乎和ICacheStrategy的沒(méi)有太大分別,實(shí)際上,這個(gè)類保存了一個(gè)對(duì)于ICacheStrategy類型實(shí)例的引用,最后一步的實(shí)際工作,都委托給了ICacheStrategy去完成。而在此之前各個(gè)方法的工作主要是由 Xml結(jié)點(diǎn)到Hashtable的映射(這里說(shuō)是Hashtable,是因?yàn)樗亲髡咛峁┑囊粋€(gè)默認(rèn)實(shí)現(xiàn),當(dāng)然也可以是其他)。 

類型實(shí)現(xiàn) 
我們首先看DefaultCacheStrategy,它實(shí)現(xiàn)了ICacheStrategy接口,并使用Hashtable存儲(chǔ)對(duì)象。  

復(fù)制代碼 代碼如下:

public class DefaultCacheStrategy : ICacheStrategy {     
    private Hashtable objectStore;     

    public DefaultCacheStrategy() {     
       objectStore = new Hashtable();     
    }     

    public void AddItem(string key, object obj) {     
       objectStore.Add(key, obj);     
    }     

    public object GetItem(string key) {     
       return objectStore[key];     
    }     

    public void RemoveItem(string key) {     
       objectStore.Remove(key);     
    }     
}    

接下來(lái)我們一步步地看Cache類的實(shí)現(xiàn),下面是Cache類的字段以及構(gòu)造函數(shù)(注意為私有)。 Java復(fù)制代碼
復(fù)制代碼 代碼如下:

public class Cache {     
    private XmlElement rootMap;             // 動(dòng)態(tài)構(gòu)建的 Xml文檔 的根結(jié)點(diǎn)     
    private ICacheStrategy cacheStrategy;   // 保存對(duì)ICacheStrategy的引用     
    public static readonly Cache Instance = new Cache();  // 實(shí)現(xiàn)Singleton模式     
    private XmlDocument doc = new XmlDocument();   // 構(gòu)建 Xml文檔     

    // 私有構(gòu)造函數(shù),用來(lái)實(shí)現(xiàn)Singleton模式     
    private Cache() {     
       // 這里應(yīng)用了Strategy模式。     
       // 改進(jìn):可以將使用何種Strategy定義到app.config中,然后使用反射來(lái)動(dòng)態(tài)創(chuàng)建類型     
       cacheStrategy = new DefaultCacheStrategy();     

       // 創(chuàng)建文檔根結(jié)點(diǎn),用于映射 實(shí)際的數(shù)據(jù)存儲(chǔ)(例如Hashtable) 和 Xml文檔     
       rootMap = doc.CreateElement("Cache");     

       // 添加根結(jié)點(diǎn)     
       doc.AppendChild(rootMap);     
    }     
    // 略...     
}  

相關(guān)文章

最新評(píng)論