设计模式——单例模式和原型模式

1.单例模式

特点:就是整个程序有且只有一个实例,该类负责创建自己的对象,并且只有一个对象被创建

 懒汉式:必须调用CreateInstance()才能创建实例

 

    public class Singleton
    {

        /// <summary>
        /// 2.指定一个静态字段
        /// </summary>
        private static Singleton singleton = null;


        private static object Singleton_Lock = new object();
 /// <summary>
        /// 懒汉式学习
        /// </summary>
        /// <returns></returns>
        public static Singleton CreateInstance()
        { 
            if (singleton == null)
            { 
                lock (Singleton_Lock)//反多线程
                {
                    if (singleton == null)
                    {
                        singleton = new Singleton();
                    }
                }
            }
            return singleton;
        }
}

问题:如果调用静态方法,可能存在未创建对象的情况

饿汉式

    public class SingletonThird
    {

        /// <summary>
        /// 在类被调用的时候,执行且只执行一一次
        /// </summary>
        static SingletonThird()
        {
            singleton = new SingletonThird();
        }
         
        /// <summary>
        /// 3.饿汉式写法
        /// </summary>
        private static SingletonThird singleton = null;
         
        /// <summary>
        /// 1.私有化构造函数
        /// </summary>
        private SingletonThird()
        {
          
        }

    }

 

可以动态创建单例模式

1.泛型单例模型

 public class BaseSingleton<T> where T : new()
    {
        protected static T _Instance;

        private static object Singleton_Lock = new object();
        public static T CreateInstance()
        {
            if (_Instance == null)
            {
                lock (Singleton_Lock)//反多线程
                {
                    if (_Instance == null)
                    {
                        _Instance = new T();
                    }
                }
            }    
            return _Instance;
        }
    }

2.要实现的单列类继承这个模型

   public class SingletonFourth : BaseSingleton<SingletonFourth>
    {
}

2.原型模式

特点:直接内存复制生产新的对象

    public class SingletonFifth
    {
        /// <summary>
        /// 2.饿汉式写法
        /// </summary>
        private static SingletonFifth singleton = new SingletonFifth();
         
        /// <summary>
        /// 1.私有化构造函数
        /// </summary>
        private SingletonFifth()
        {
        }

        /// <summary>
        /// 懒汉式学习
        /// </summary>
        /// <returns></returns>
        public static SingletonFifth CreateInstance()
        {  
            return (SingletonFifth)singleton.MemberwiseClone();  //基于内存克隆
        }

    }

先用单例模式生成一个模板对象,然后直接内存克隆,可以优化性能提高速度

posted @ 2022-07-04 22:44  乌柒柒  阅读(43)  评论(0编辑  收藏  举报