Simpler Singleton Based on Jon Skeet's Singleton
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?
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".
链接地址: http://www.djcxy.com/p/51106.html上一篇: 内部函数访问外部函数的变量