3

Considering the 'standard' C# implementation of a singleton pattern with type initialisation:

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

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

    private Singleton() { }
}

Is there any point in the static property? If the static field is marked as readonly, then surely it cannot be written to from anywhere, including from outside the class. For a more terse implementation, would this work?:

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

It seems fine to me but I've only ever seen the top one used so I wonder if there is anything wrong that I have missed.

4

3 回答 3

9

Is there any point in the static property?

Yes. It hides the implementation detail that the value is retrieved from a field in the exact same class. If you expose the field, you're stuck with that implementation forever (assuming you can't later change/rebuild all code referring to it). If you use a property, you could later:

  • Change to use Lazy<T>
  • Use a field within a nested class to get potentially lazier initialization if you want to have other static methods in the class
  • Use some new and funky scheme yet to be devised

Basically, with a property you've got options for future change. With a field, you haven't.

I used not to think this was a relevant difference, but in Noda Time I've had situations where complex type initialization ordering issues have made it really important that I can control this sort of thing. Where I've exposed a public static readonly field in an earlier version, I've later regretted it :(

A public static readonly field works in terms of still being a singleton - it just gives you less control.

As an aside, you may wish to add an empty static constructor to your class. See my articles on singleton implementations and beforefieldinit for more details.

于 2013-08-23T08:05:21.123 回答
0

In case of the Singleton pattern it's not very harmful to have a public readonly field rather than just a getter.

The reason the 'standard' implementation is using a getter is to be consistent with the rest of public getters and make you adopt good habits for all the other cases where a getter is more appropriate than a poublic field (for adding functionality without changing the interface for example)

于 2013-08-23T08:06:09.387 回答
-2

Readonly will mean that it is an instance variable that cant be written to, static is a variable that can be read without instantiating the object. For example you would call them as follows:

//Readonly
var readonlySingleton = new singleton();
var result = readnlySingleton.Instance;

//static readonly
var result = singleton.Instance;
于 2013-08-23T08:05:31.930 回答