网站制作公司资质/编程培训机构加盟哪家好
多用于创建复杂的或者耗时的实例,因为这种情况下,复制一个已经存在的实例使程序运行更高效;或者创建值相等,只是命名不一样的同类数据。
从原型模式的概念中,我们可以看到,在这个模式里,拷贝是个很重要的概念,即在不创建对象的情况下,返回一个已有对象,这就是拷贝去实现的,在面向对象的编程世界里,拷贝分为浅拷贝和深拷贝,如果希望对两者有更深入的认识,
可以阅读我的这篇文章《不忘本~浅拷贝和深拷贝》。
何时能用到它?
当你一个大对象被创建后,它可以在程序里被使用多次,而使用的时候可能有些属性值会发生变化,这里,你不需要重新去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();
结果截图
本文转自博客园张占岭(仓储大叔)的博客,原文链接:谈谈设计模式~原型模式(Prototype),如需转载请自行联系原博主。