设为首页 加入收藏

TOP

谈谈设计模式~原型模式(Prototype)
2019-09-03 03:34:03 】 浏览:49
Tags:谈谈 设计模式 原型 模式 Prototype

返回目录

原型模式是创建型模式的一种,其特点在于通过“复制”一个已经存在的实例来返回新的实例(clone),而不是新建(new)实例。被复制的实例就是我们所称的“原型”,这个原型是可定制的。

原型模式多用于创建复杂的或者耗时的实例,因为这种情况下,复制一个已经存在的实例使程序运行更高效;或者创建值相等,只是命名不一样的同类数据。

从原型模式的概念中,我们可以看到,在这个模式里,拷贝是个很重要的概念,即在不创建对象的情况下,返回一个已有对象,这就是拷贝去实现的,在面向对象的编程世界里,拷贝分为浅拷贝和深拷贝,如果希望对两者有更深入的认识,

可以阅读我的这篇文章《不忘本~浅拷贝和深拷贝》。

何时能用到它?

当你一个大对象被创建后,它可以在程序里被使用多次,而使用的时候可能有些属性值会发生变化,这里,你不需要重新去new这个对象,而可以使用原型模式去克隆这个对象,这样,可以提交程序的性能。

策略模式的结构图

 

策略模式实现说明

CarPrototype:抽象原型,定义一个克隆的方法,返回规定的原型

ConcteteCarPrototype:具体原型,实现了抽象原来的克隆,并返回了这类抽象原型,在具体原型中,还提供了某体的属性和方法等

CarManagerL:原型管理器,这个管理员用于被前台(UI)去调用,它用来存储原型集合

策略模式的C#实现

#region 原型模式
    abstract class CarPrototype
    {
        public abstract CarPrototype Clone();
    }

    class ConcteteCarPrototype : CarPrototype
    {
        private string _body, _color, _wheal;
        public ConcteteCarPrototype(string body, string color, string wheal)
        {
            this._body = body;
            this._color = color;
            this._wheal = wheal;
        }
        public override CarPrototype Clone()
        {
            //实现浅表拷贝
            return (CarPrototype)this.MemberwiseClone();
        }
        public void Display(string _carName)
        {
            Console.WriteLine("{0}'s Cart Values are: {1},{2},{3}",
                _carName, _body, _color, _wheal);
        }
    }

    class CarManager
    {
        Hashtable colors = new Hashtable();
        public CarPrototype this[string name]
        {
            get
            {
                return (CarPrototype)colors[name];
            }
            set
            {
                colors.Add(name, value);
            }
        }
    }


    #endregion

调用代码

 CarManager colormanager = new CarManager();

            //初始化
            colormanager["奥迪"] = new ConcteteCarPrototype("德国", "黑色", "四轮驱动");
            colormanager["奇端"] = new ConcteteCarPrototype("中国", "白色", "前轮驱动");

            //调用

            ConcteteCarPrototype c1 = (ConcteteCarPrototype)colormanager["奇端"].Clone();
            c1.Display("奇端");

            Console.ReadLine();

结果截图

 

返回目录

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇设计模式-生成器模式 下一篇【装饰者模式】Decorator Pattern

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目