2013-12-17 42 views
0

下面的胎面是否以單件模式安全運行?我使用第四個單例模式在http://csharpindepth.com/Articles/General/Singleton.aspxSingleton中的輸出參數

我擔心使用輸出參數將打破整個主體。

public sealed class eCacheContent 
{ 
     private static readonly eCacheContent instance = new eCacheContent(); 
     private ICacheManager _Cache = CacheFactory.GetCacheManager(ConfigurationManager.AppSettings["ContentCache"].ToString()); 
     // for access method control locking 
     private static object syncRoot = new object(); 

     // Explicit static constructor to tell C# compiler 
     // not to mark type as beforefieldinit 
     static eCacheContent() { } 

     private eCacheContent() { } 

     public static eCacheContent Instance 
     { 
      get 
      { 
       return instance; 
      } 
     } 

     public bool TryGetValue(string key, out eContent output) 
     { 
      lock (syncRoot) 
      { 

       if (Contains(key)) 
       { 
        ObjectCloner helper = new ObjectCloner(); 
        eContent tmp = (eContent)this._Cache.GetData(key); 
        output = helper.Clone(tmp); 
        return true; 
       } 


       output = new eContent(); 
       return false; 
      } 
     } 

     public void Add(string key, object value) 
     { 
      // Initiase the helper class for cloning 
      if (CheckKeyIfValid(key)) 
      { 
       ObjectCloner helper = new ObjectCloner(); 
       // Remove if already exist 
       this.Remove(key); 
       // Add carbon copy 
       _Cache.Add(key, helper.Clone(value)); 
      } 
     } 

     public void Flush() 
     { 
      _Cache.Flush(); 
     } 

     private bool Contains(string key) 
     { 
      if (CheckKeyIfValid(key)) 
       return _Cache.Contains(key); 
      else 
       return false; 
     } 

     private void Remove(string key) 
     { 
      if (Contains(key)) 
      { 
       _Cache.Remove(key); 
      } 
     } 

     private bool CheckKeyIfValid(string key) 
     { 
      if ((key != null) && (key.Trim().Length != 0)) 
       return true; 

      return false; 
     } 

    } 
+0

你的方法是* instance *方法,而不是'static' - 我認爲這是一個錯誤? – James

+0

我會說這確實是一個壞主意。當你鎖定這段代碼時,其他線程可能正在訪問你的「out」變量。不要試圖鎖定這個var,因爲這可能會導致死鎖。所以我會說:壞主意。無論如何,爲什麼使用ref呢?只需返回字符串。這不是C++,成員是引用計數。 – Samuel

+0

我看到我的思路出錯了。它總是有幫助的獲得一個外觀...謝謝 – user3111634

回答

0

我擔心使用輸出參數將打破整個主體。

你認爲一個out參數打破了單例的原理是什麼?通過definition單個類「限制一個類的實例化到一個對象」 - 您的Instance屬性確保。

您的TryGetValue方法是用於提取緩存版本eContent的輔助方法,這與您的eCacheContent類完全分離。

+0

是的,我意識到只有一個。在任何示例中都沒有看到輸出peratermer,並且不確定它是否可能在用戶遇到碰撞頭時共享。由於所有的內容對象都被緩存,所以我期待這個單例有很多流量。 – user3111634