zoukankan      html  css  js  c++  java
  • 单例模式

    学习圣杰的文章  我是独一无二的『单例模式

    其中的锁机制单例 和 由此引出的 泛型单例子模式 挺棒 

    泛型单利模式如下:

    /// <summary>
        /// 泛型单例模式的实现
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public class GenericSingleton<T> where T : class//,new ()
        {
            private static T instance;
    
            private static readonly object Locker = new object();
    
            public static T GetInstance()
            {
                //没有第一重 instance == null 的话,每一次有线程进入 GetInstance()时,均会执行锁定操作来实现线程同步,
                //非常耗费性能 增加第一重instance ==null 成立时的情况下执行一次锁定以实现线程同步
                if (instance == null)
                {
                    //Double-Check Locking 双重检查锁定
                    lock (Locker)
                    {
                        if (instance == null)
                        {
                            //instance = new T();
                            //需要非公共的无参构造函数,不能使用new T() ,new不支持非公共的无参构造函数 
                            instance = Activator.CreateInstance(typeof(T), true) as T;//第二个参数防止异常:“没有为该对象定义无参数的构造函数。”
                        }
                    }
                }
                return instance;
            }

     但是 我对 

    //instance = new T();
    //需要非公共的无参构造函数,不能使用new T() ,new不支持非公共的无参构造函数 
     instance = Activator.CreateInstance(typeof(T), true) as T;//第二个参数防止异常:“没有为该对象定义无参数的构造函数。”

    有点不理解

  • 相关阅读:
    无锁编程(五)
    Linux Kernel CMPXCHG函数分析
    无锁编程(四)
    无锁编程(三)
    无锁编程(二)
    无锁编程(一)
    无锁编程
    Linux同步机制
    Linux同步机制
    bootstrap css编码规范
  • 原文地址:https://www.cnblogs.com/wholeworld/p/8007209.html
Copyright © 2011-2022 走看看