2011-04-15 86 views
1

我寫了一段關於單例模式實現的代碼。不確定其正確性。請給點建議。謝謝。單例實現

public class Singleton 
{ 
    public Singleton Instance 
    { 
     get 
     { 
      if (_instance == null) 
      { 
       if (_mutexCreation.WaitOne(0)) 
       { 
        try 
        { 
         if (_instance == null) 
         { 
          _instance = new Singleton(); 
         } 
        } 
        finally 
        { 
         _mutexCreation.ReleaseMutex(); 
         _eventCreation.Set(); 
        } 

       } 
       else 
       { 
        _eventCreation.WaitOne(); 
       } 
      } 
      return _instance; 
     } 
    } 

    private Singleton() { } 

    private static Singleton _instance; 
    private static Mutex _mutexCreation = new Mutex(); 
    private static ManualResetEvent _eventCreation = new ManualResetEvent(false); 
} 
+0

請用任何語言對此進行標記,以便從該社區接收專家。 :) – sarnold 2011-04-15 08:31:24

+0

它看起來像C#... – shoosh 2011-04-15 08:35:42

+0

我剛剛標記。 :) – lichaoir 2011-04-15 08:49:10

回答

3
public class Singleton 
{ 
    private static object _syncRoot = new object(); 

    public Singleton Instance 
    { 
     get 
     { 
      if (_instance == null) 
      { 
       lock (_syncRoot) 
       { 
        if (_instance != null) 
         return _instance; 

        _instance = new Singleton(); 
       } 
      } 
      return _instance; 
     } 
    } 

    private Singleton() { } 
    private static Singleton _instance; 
} 

如果你不想使用延遲加載,乾脆直接在靜態構造函數創建一個新的實例。

+0

謝謝,我知道,我想要懶惰。我在想如果這可能比使用互斥鎖(或關鍵區域)的傳統雙重檢查實現更有效。 – lichaoir 2011-04-15 09:04:08

+0

不要做過早的優化。這個代碼更可讀,因此更好。 – jgauffin 2011-04-15 09:05:36

+0

讓我進一步闡述。延遲加載通常意味着該對象要麼消耗大量資源,要麼加載一些CPU。相比之下,鎖定機制需要多少時間並不重要。 – jgauffin 2011-04-15 09:09:18