设计模式实例与代码:Prototype模式
来源:互联网 发布:金本位 知乎 编辑:程序博客网 时间:2024/06/06 12:38
意图/定义:通过复制一个原型的实例来创建新的对象,而不是新建新实例,被复制的实例称之谓原型
问题:当新建一个实例步骤较多或代价较高,而复制一个已有实例比较快捷或代价较低
解决方案:为对象原型提供复制自己的操作
参与者与协作者:具体原型需要实现复制自己对象的操作,客户只请求已有原型复制其自身,即得到新的实例
效果:简化了客户对于创建新对象所需要了解的知识,客户不再需要重新自己费劲的创建一个新实例(如传递各种初始化参数)
实现:创建需要可以自我复制的类,为这些类提供clone实现,使得其可以以合适的方式返回自己的一个复本,当需要新对象的时候,从原型实例复制即可。
结构性的示例代码如下:
using System; namespace Prototype{ /// <summary> /// MainApp startup class for Structural /// Prototype Design Pattern. /// </summary> class MainApp { /// <summary> /// Entry point into console application. /// </summary> static void Main() { // Create two instances and clone each ConcretePrototype1 p1 = new ConcretePrototype1("I"); ConcretePrototype1 c1 = (ConcretePrototype1)p1.Clone(); Console.WriteLine("Cloned: {0}", c1.Id); ConcretePrototype2 p2 = new ConcretePrototype2("II"); ConcretePrototype2 c2 = (ConcretePrototype2)p2.Clone(); Console.WriteLine("Cloned: {0}", c2.Id); // Wait for user Console.ReadKey(); } } /// <summary> /// The 'Prototype' abstract class /// </summary> abstract class Prototype { private string _id; // Constructor public Prototype(string id) { this._id = id; } // Gets id public string Id { get { return _id; } } public abstract Prototype Clone(); } /// <summary> /// A 'ConcretePrototype' class /// </summary> class ConcretePrototype1 : Prototype { // Constructor public ConcretePrototype1(string id) : base(id) { } // Returns a shallow copy public override Prototype Clone() { return (Prototype)this.MemberwiseClone(); } } /// <summary> /// A 'ConcretePrototype' class /// </summary> class ConcretePrototype2 : Prototype { // Constructor public ConcretePrototype2(string id) : base(id) { } // Returns a shallow copy public override Prototype Clone() { return (Prototype)this.MemberwiseClone(); } }}
- 设计模式实例与代码:Prototype模式
- [设计模式](四):建造者模式(Builder)与原型模式(Prototype)[含Kotlin深克隆实例代码]
- 设计模式与实例代码:Facade模式
- 设计模式与实例代码:Adapter模式
- 设计模式与实例代码:Strategy模式
- 设计模式与实例代码:Decorator模式
- 设计模式与实例代码:Bridge模式
- 设计模式与实例代码:Observer模式
- 设计模式实例与代码:Builder模式
- 设计模式与实例代码:Composite模式
- 设计模式与实例代码:Visitor模式
- 设计模式与实例代码:Proxy模式
- 设计模式:Prototype模式
- 设计模式-Prototype模式
- 设计模式-Prototype模式
- 设计模式 - Prototype 模式
- 设计模式-Prototype模式
- 设计模式--Prototype模式
- iOS Delegate NSNotificationCenter
- VC多媒体编程
- ActivityGroup下子Activity的布局问题
- Android SDK弱爆了---在64位Linux机器上使用的同学注意了
- Ubuntu安装Qt开发环境
- 设计模式实例与代码:Prototype模式
- 标准库中的map和set
- 如何在php中使用Libchart绘制中文的图表
- (遍历)一些基本的求和,求积,求阶乘,计数问题(流程控制语句的使用)
- 编译器参数:keep-generated-actionscript 作用于MXML文件
- c++第八周【任务1-3】实现复数类中的运算符重载
- PHP内核每天挖一点-数组的底层结构
- 无题
- JCo/JBOSS/JCA Adaptor集成笔记