静态内部类和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()
     {
     }
 } 

 

posted @ 2016-04-16 23:02  zslm___  阅读(556)  评论(0编辑  收藏  举报