原版设计模式之原型模式

Intent (定义)

Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.(指定使用原型实例创建的对象类型,并通过拷贝此实例创建一个新对象)

Motivation (举例)

在这里插入图片描述
上述音谱编辑器,创建音谱为例,需要使用图形工具创建不同的音符图形,并绘制在不同的位置。
首先就是GraphicTool并不知道需要绘制哪种音符,如果为每个音符创建一个工具类,比如全音符, WholeGraphicTool,半音符,HalfGraphicTool。
如果为每个音符创建一个绘图工具,那么就将产生很多的Tool。
The solution lies in making GraphicTool create a new Graphic by copying or “cloning” an instance of a Graphic subclass.(解决方案就是,让GraphicTool通过clone图形子类的实例来创建一个新的图形)
We call this instance a prototype. (我们称这个实例为原型
上述参考代码

Applicability (适用情况)

  • when the classes to instantiate are specified at run-time, for example, by dynamic loading; (运行时指定要加载的类,例如:动态加载)
  • to avoid building a class hierarchy of factories that parallels the class hierarchy of products; (为了避免创建和产品结构相似的工厂结构) 即上述案例为了每个音符都要创建一个Tool的情况。
  • when instances of a class can have one of only a few different combinations of state.(当实例化的类只有少数几种状态时)
    It may be more convenient to install a corresponding number of prototypes and clone them rather than instantiating the class manually, each time with the appropriate state.(预先初始化实例,并使用clone方式,比每次有合适状态都要手动实例化类时更方便。) 预先实例化 > 手动实例化

在这里插入图片描述

Participants (类说明)

  • Prototype (Graphic) (原型类)
    • declares an interface for cloning itself. (声明一个用于克隆自己的接口)
  • ConcretePrototype (Staff, WholeNote, HalfNote) (具体原型类)
    • implements an operation for cloning itself. (实现克隆自己的操作)
  • Client (GraphicTool) (客户端)
    • creates a new object by asking a prototype to clone itself.(通过要求原型实例克隆自己来创建一个新对象)

Collaborations (约定)

A client asks a prototype to clone itself. (客户端要求原型实例克隆自己来创建对象)

Related Patterns (相关模式)

Prototype and Abstract Factory (99) are competing patterns in some ways, as we discuss at the end of this chapter. (正如最后一章所述,原型模式和抽象工厂模式是竞争模式)
They can also be used together, however. An Abstract Factory might store a set of prototypes from which to clone and return
product objects. (不过,他们也可以组合使用。例如,抽象工厂预先实例化一些类,然后通过clone返回产品对象。)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值