Different singelton implementations
When I was introduced to the singleton pattern, this was the way to implement it:
public class MySingleton
{
private MyStingleton instance;
private MySingleton()
{
//constructor
}
public static MySingleton GetInstance()
{
if(instance== null)
{
instance = new MySingleton();
}
return instance;
}
}
What is the advantage doing it this way, compared to this:
public class My开发者_开发技巧Singleton
{
public static readonly MyStingleton Instance = new MySingleton();
private MySingleton()
{
//constructor
}
}
The first example is not thread safe. You may take a look at the following article.
Both of those singleton implementations are unsafe, and I see no benefit from using the second one over the first one.
You should probably check out this link: http://www.yoda.arachsys.com/csharp/singleton.html where a number of singleton implementations is listed, for each one is explained why they are good or bad.
The final correct singleton is this:
public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
In the first one, the instance is not created until you call the GetInstance static method. you create the instance just when you call this method.
In the second one the instance is a constant, is conceptually different.
used to use the first one, is the pattern I have always seen, and you can control when the instance is created.
精彩评论