阅读 276

C# 设计模式——单例模式(Singleton)

     单例(Singleton)模式:某个类只能生成一个实例,该类提供了一个全局访问点供外部获取该实例,
     其拓展是有限多例模式。
复制代码

饿汉单例

  // 饿汉式单例 (开发中最常用,除非有早于单列类实例化时就引用了其他静态成员的情况。)
 public sealed class HungryMan{ 
  // 将instance设置成了readonly,保证代码的高效、短小。
   private static readonly HungryMan instance = new HungryMan();
   /// <summary>
   /// 显式的静态构造函数用来告诉C#编译器在其内容实例化之前不要标记其类型
   /// </summary>
   static HungryMan() { }
   private HungryMan() { }
   public static HungryMan Instance { get { return instance; } }
 }
复制代码

懒汉单例

public sealed class LazyMan
{
    private LazyMan() { }
    public static LazyMan Instance { get { return Nested.instance; } }
    private class Nested
    {
        static Nested() { }
        internal static readonly LazyMan instance = new LazyMan();
    }
}
复制代码
    //DCL懒汉模式(double check lock)
public sealed class DCLLazyMan
{
    private static DCLLazyMan instance = null;
    // 使用volatile关键字,标记
    private static readonly object obj = new object();
    //private static volatile object obj = new object();
    private DCLLazyMan() { }
    public static DCLLazyMan Instance
    {
        get
        {
            if (instance == null)
            {
                lock (obj)
                {
                    if (instance == null)
                    {
                        instance = new DCLLazyMan();
                    }
                }
            }
            return instance;
        }
    }
}
复制代码
    //.NET 4 Lazy type 特性(懒汉模式)
    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() { }
}
    

复制代码
文章分类
后端
文章标签