设计模式(二)——原型模式

原型模式是用于创建重复的对象,同时能保证性能,属于创建型模式,提供了一种创建对象的最佳方式。

意图:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

主要解决:在运行期间创建和删除原型。

优点:提高性能,逃避了构造函数的约束。

        #region 原型模式
        public abstract class PrototypeClass {
            public PrototypeClass(string Name)
            {
                this.Name = Name;
            }

            public string Name { set; get; }

            public abstract PrototypeClass Clone();
        }

        public class Prototype1 : PrototypeClass
        {
            public Prototype1(string Name) : base(Name)
            {

            }
            public override PrototypeClass Clone()
            {
                return (PrototypeClass)this.MemberwiseClone();
            }
        }
        public class Prototype2 : PrototypeClass
        {
            public Prototype2(string Name) : base(Name)
            {

            }
            public override PrototypeClass Clone()
            {
                return (PrototypeClass)this.MemberwiseClone();
            }
        }
        #endregion
static void Main(string[] args)
        {
            Prototype1 prototype1 = new Prototype1("a");
            var PrototypeClass1 = prototype1.Clone();
            //PrototypeClass1.Name = "a"
            Prototype2 prototype2 = new Prototype2("b");
            var PrototypeClass2 = prototype2.Clone();
            //PrototypeClass2.Name = "b"
            Console.ReadKey();
        }

 暂时只能感受到创建对象的时候可以隐藏一下抽象原型,感觉没多大作用啊,可能是我理解太浅薄了吧,明天找个时间继续看看

2019年10月25日00:30:31

往后三个星期,每天复习一个设计模式,Go

猜你喜欢

转载自www.cnblogs.com/yuchenghao/p/11735889.html