Ken*_*hou 7 c# design-patterns
使用C#实现的Singleton可以是:
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果我使用静态来实现它像:
public static class Globals{
public static Singleton Instance = new Singleton();
}
Run Code Online (Sandbox Code Playgroud)
通过这种方式,app也应该只获得整个应用程序的一个实例.那么这两种方法之间的区别是什么?为什么不直接使用静态成员(更简单直接)?
如果您使用第二种方法:
public static class Globals{
public static Singleton Instance = new Singleton();
}
Run Code Online (Sandbox Code Playgroud)
什么都没有阻止某人做:
Singleton anotherInstance = new Singleton(); // Violates singleton rules
Run Code Online (Sandbox Code Playgroud)
你也没有得到你的第一个版本(尝试)实现的延迟初始化,加上你正在使用一个公共字段,如果你需要改变一个值时发生的事情,将来不会给你相同的灵活性取了.
请注意,.NET 4提供了一种更好的方法来制作单例:
public class Singleton
{
private static readonly Lazy<Singleton> instance = new Lazy<Singleton>( ()=> new Singleton());
private Singleton() {}
public static Singleton Instance
{
get
{
return instance.Value;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这很好,因为它完全是懒惰的,完全是线程安全的,但也很简单.