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;
        }
    }
  • 相关阅读:
    sqlserver中函数和存储过程的区别
    sql 经典面试题
    sqlserver 时间处理函数
    在GROUP BY中"做文章"(五种中简答方法!)
    SQL 非等价连接
    GROUP BY 两个字段(或者多个字段的时候)
    WCF-错误集合001
    DOM
    DOM的排他功能及显示隐藏功能
    预解析
  • 原文地址:https://www.cnblogs.com/mathyk/p/9448458.html
Copyright © 2011-2022 走看看