这是辛格尔顿执行正确,线程安全的? [英] Is this Singleton implementation correct and thread-safe?

查看:100
本文介绍了这是辛格尔顿执行正确,线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是单执行正确,线程安全的?



  Class类
{
公共静态只读类实例;

静态类()
{
实例=新的Class();
}

私有类(){}
}


解决方案

从技术上讲,你的版本应该工作。不过,我不建议你Singleton类中暴露公共领域,更喜欢使用属性(只有一个getter)。这将有助于面向未来的API,如果以后需要做出改变。我还建议密封的单实施,继承单个类几乎总是一个坏主意和有问题的。



我个人而言,使用,如果你在C#以下, 再打靶.NET 3.5或更早版本:

 公共密封类辛格尔顿
{
静态只读Singleton实例=新辛格尔顿();

公共静态Singleton实例
{
得到
{
返回实例;
}
}

静态辛格尔顿(){}
私人辛格尔顿(){}
}

如果您正在使用.NET 4中,您可以通过使这甚至对自己更容易懒惰< T>

 公共密封类辛格尔顿
{
私人静态只读懒<单身>例如=新懒人<辛格尔顿>(()=>新建辛格尔顿());
私人辛格尔顿(){}
公共静态Singleton实例{{返回instance.Value; }}
}



在.NET 4的版本也有被完全懒惰的优势 - 即使你的辛格尔顿类有它们的实例属性的访问之前使用的其他静态方法。你可以做一个完全懒.NET 3.5的版本,以及通过使用一个私人的,嵌套类。 乔恩斯基特证明了这一点在他的博客


Is this singleton implementation correct and thread-safe?

class Class
{
    public static readonly Class Instance;

    static Class()
    {
        Instance = new Class();
    }

    private Class() {}
}

解决方案

Technically, your version should work. However, I would not recommend exposing a public field within your Singleton class, and prefer using a Property (with a getter only). This will help future-proof your API if you need to make changes later. I also recommend sealing any singleton implementation, as subclassing a singleton class is almost always a bad idea and problematic.

I would, personally, use the following in C#, if you're targetting .NET 3.5 or earlier:

public sealed class Singleton
{
    static readonly Singleton instance = new Singleton();

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

    static Singleton() { }
    private Singleton() { }
}

If you're using .NET 4, you can make this even easier for yourself via Lazy<T>:

public sealed class Singleton
{
     private static readonly Lazy<Singleton> instance = new Lazy<Singleton>( () => new Singleton() );
     private Singleton() {}
     public static Singleton Instance { get { return instance.Value; } }
}

The .NET 4 version also has the advantage of being fully lazy - even if your Singleton class has other static methods which are used prior to the access of the "Instance" property. You can do a fully-lazy .NET 3.5- version, as well, by using a private, nested class. Jon Skeet demonstrated this on his blog.

这篇关于这是辛格尔顿执行正确,线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆