更简单的单身人士基于Jon Skeet的单身人士

时间:2017-02-15 19:26:18

标签: c# .net singleton

我的代码中需要一个单例。我阅读Jon Skeet关于Singletons的page并根据他的建议选择了这个模型(#4):

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

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton(){}

    private Singleton(){}

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

然后我通过几个步骤来修改它以适合我的场景:

第1步:我不需要延迟实现,因此我取出了静态构造函数(正如Jon在他的文章末尾所建议的那样):

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

    private Singleton(){}

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

第2步:然后我将“实例”Singleton类换成了我正在使用的Logging类:

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

    private Singleton(){}

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

第3步: Resharper告诉我,我应该为我的“Instance”属性使用自动属性:

public sealed class Singleton
{
    private Singleton(){}

    public static Logging Instance { get; } = new Logging();
}

第4步: Resharper告诉我应该将其切换为静态类:

public static class Singleton
{
    public static Logging Instance { get; } = new Logging();
}

我剩下的与原版完全不同。我知道在设置线程安全的Singleton时很容易出错。

所以我想问:我的任何步骤是否使我的课程不再是一个好的Singleton实现?

1 个答案:

答案 0 :(得分:3)

  

我的任何步骤是否使我的课程不再是一个好的Singleton实现?

是的,他们这样做。

您在步骤1中删除的行为无论如何都是一个实现细节。删除空的静态构造函数很好;如果你想强制懒惰初始化,Lazy<T>是一个更好的方法,即使它有更多的开销。

在第2步,您的对象完全停止了单身,因为您无法再控制对象的实例数(Logging)。

我说完全不是单身人士就有资格成为&#34;不是一个好的单身人士实施&#34;。

相关问题