2011-04-15 104 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