原版设计模式之原型模式
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返回产品对象。)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?