2010-11-21 60 views
1

我一直在阅读有关模式,并试图实施Singleton我的单例实现是否正确? c#

我的实施是否正确?我如何改进它?有在网络上这么多的实施............

public sealed class SingletonProxy 
     { 
      private static IInfusion instance; 

      static SingletonProxy() { } 

      SingletonProxy() { } 

      public static IInfusion Instance 
      { 
       get 
       { 
        if(instance == null) 
        { 
         instance = XmlRpcProxyGen.Create<IInfusion>(); 
        } 
        return instance; 
       } 
      } 
     } 
+2

它不是线程安全的。 – Ani 2010-11-21 13:35:04

+0

为什么这不是线程安全的,你将如何修改它? – Gigapr 2010-11-21 14:05:53

+0

正如其他人指出的那样,您应该阅读Jon Skeet关于此主题的网页。锁定,或者甚至更好,仔细检查锁定,在这里会有所帮助。 – Ani 2010-11-21 14:42:13

回答

2

...并且还有谁同意this article提供的SO这么多相同的问题,所以很多人最佳方案!

+0

+1。我通常使用第二个版本(简单的线程安全) – 2010-11-21 13:40:55

1

因为我们现在有System.Lazy类,我倾向于使用这个实现:

public sealed class SingletonProxy 
{ 
    private static readonly Lazy<IInfusion> instance 
      = new Lazy<IInfusion>(XmlRpcProxyGen.Create<IInfusion>); 

    public static IInfusion Instance 
    { 
     get { return instance.Value; } 
    } 
}