Two questions on Singleton C#
Consider the following code
publ开发者_Go百科ic sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
public static Singleton Instance { get { return instance; } }
static Singleton() {}
private Singleton() {}
}
Question
1) Here what is the purpose of static constructor ? (I know static constructor will be called before the first instance of the class is created).But in the context of above code can't i use it without the static constructor?
2) I heard that one of the advantages of singleton is that it can be extended into factory. Since it is a sealed class ,how will you extend it into factory?can you give some example?
The static constructor ensures that the singleton really isn't constructed before it's used. If the static constructor isn't present, the CLR has a lot more leeway about when it runs the type initializer. See my article on beforefieldinit and my blog post about .NET 4 type initialization changes for more info.
As for turning a singleton into a factory - you'd really have to give more context. Your Instance
property could choose whether to always return a reference to the same object or not, I suppose...
There is no need for a static constructor.SKEET!- I've never heard of that. You can't, obviously, if the class is sealed. But you could moderately easily rewrite it as a factory, as there is only one way to instantiate it--through a property. Change that into a method, and you have the starts of a factory. The method may return the same instance each time, or may return an instance from a pool, or do whatever it wants.
I wouldn't suggest you have a factory property, as properties shouldn't be doing too much work.
精彩评论