Simpler Singleton Based on Jon Skeet's Singleton

£可爱£侵袭症+ 提交于 2019-12-10 17:09:51

问题


I need a singleton in my code. I read Jon Skeet's page on Singletons and selected this model (#4) based on his recommendation:

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

I then went through a few steps to modify this to fit my scenario:

Step 1: I don't need a lazy implementation, so I took out the static constructor (as suggested by Jon at the end of his article):

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

    private Singleton(){}

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

Step 2: I then swapped out the "instance" Singleton class with the Logging class I am working with :

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

    private Singleton(){}

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

Step 3: Resharper then told me that I should use an auto property for my "Instance" property:

public sealed class Singleton
{
    private Singleton(){}

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

Step 4: Resharper then told me I should switch this to a static class:

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

What I am left with is very different from the original. I know that it is very easy to get things wrong when setting up a thread safe Singleton.

So I wanted to ask: Do any of my steps make my class not a good Singleton implementation any more?


回答1:


Do any of my steps make my class not a good Singleton implementation any more?

Yes, they do.

The behavior you removed in Step #1 is an implementation detail anyway. Removing the empty static constructor is fine; if you want to force lazy init, Lazy<T> is a better way anyway even if it has slightly more overhead.

At Step #2, your object stopped being a singleton at all, because you no longer have control over how many instances of the object (Logging) are created.

I'd say that not being a singleton at all qualifies as being "not a good Singleton implementation".



来源:https://stackoverflow.com/questions/42258375/simpler-singleton-based-on-jon-skeets-singleton

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!