静态内部类和Lazy<T>优雅实现单例
public class Singleton
{
private Singleton()
{
}
public static Singleton GetInstance()
{
return ConcreateSingleton.instance;
}
private static class ConcreateSingleton
{
public static Singleton instance = new Singleton();
}
}
很优雅的写法,实现了延迟加载的需要
另一种优雅写法是要用到.net 4.0里Lazy<T>
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}

浙公网安备 33010602011771号