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;//第二个参数防止异常:“没有为该对象定义无参数的构造函数。”

    有点不理解

  • 相关阅读:
    临时表学习
    再读《黄金时代》
    shell脚本获取给定年月前一月份及后一月份
    MEMORY_TARGET not supported on this system
    2013年的总结
    windows live writer试试
    入园第一篇
    工作中经常用到的几个字符串和数组操作方法
    小程序获取用户信息失败
    前端性能优化方法概括
  • 原文地址:https://www.cnblogs.com/wholeworld/p/8007209.html
Copyright © 2011-2022 走看看