我的单身实现是否正确? C#

时间:2010-11-21 13:32:12

标签: c# design-patterns

我一直在阅读有关模式的内容,我正在尝试实施Singleton

我的实施是否正确?我怎样才能改进它?网上有很多实现............

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;
                }
            }
        }

3 个答案:

答案 0 :(得分:2)

......关于SO有很多相同的问题,很多人同意this article提供最佳解决方案!

答案 1 :(得分:2)

有不同的实现。我经常在这里提到Jon Skeet的好总结:

http://www.yoda.arachsys.com/csharp/singleton.html

答案 2 :(得分: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; }
    }
}
相关问题