单例模式

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

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

泛型单利模式如下:

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

有点不理解

posted @ 2017-12-08 21:36  当年在远方  阅读(139)  评论(0编辑  收藏  举报