zoukankan      html  css  js  c++  java
  • C#单例介绍三种方法

    第一种:双if + lock

    public class Singleton
    {
      private static Singleton _Singleton = null;
      private static object Singleton_Lock = new object();
      public static Singleton CreateInstance()
      {
           if(_Singleton == null)  //双if+lock
            {
                lock (Singleton_Lock)
                {
                    Console.WriteLine("路过……");
                     if(_Singleton == null)
                     {
                        Console.WriteLine("被创建……");
                         _Singleton = new Singleton();
                     }
                }
            }       
      } 
    }
    //测试:
    TaskFactory taskFactory = new TaskFactory();
    List<Task> taskList = new List<Task>();
    for(int i=0;i<5;i++)
    {
       taskList.Add(taskFactory.StartNew( ()=>{ Singleton singleton = Singleton.CreateInstance();}));
    }
    

      

    第二种:利用静态变量实现单例模式

    public class SingletonThird
    {
           private static SingletonThird _SingletonThird = new SingletonThird();
           public static SingletonThird CreateInstance()
           {
                return _SingletonThird;
           }
    }
    

      

    第三种:利用静态构造函数实现单例模式

    public class SingletonSecond
    {
        private static SingletonSecond _SingletonSecond = null;
        static SingletonSecond()
        {
            _SingletonSecond = new SingletonSecond();
        }  
        public static SingletonSecond CreateInstance()
        {
              return _SingletonSecond;
        }
    }
  • 相关阅读:
    Ural-1018 Binary Apple Tree(树形dp+分组背包)
    Ural 1332 把圆细分+圆内切,内含关系判定
    读取图片文件(C#实现)
    使用ZXing.dll库生成二维码(C#实现)
    combobox绑定数据
    DataGridView显示日期格式问题
    夜深忽梦少年事
    Scrum角色
    Srum框架
    Scrum流程
  • 原文地址:https://www.cnblogs.com/mathyk/p/9448458.html
Copyright © 2011-2022 走看看