学习高校课程-软件设计模式-建造者模式和原型模式(lec4)

原文链接

Builder: Problem

Example: a complex object that requires laborious, step-by-step initialization of many fields and nested objects
一个复杂对象的创建通常由多个部分组成,这些部分的组合经常变化

Builder: Solution

Extract the object construction code out of its own class and move it to separate objects called builders

Further extract the series of calls to the builder steps into a separate class called director

进一步将对构建器步骤的一系列调用提取到一个名为 director 的单独类中
– The director defines the order in which to execute the building steps, while the builder provides concrete implementation
– Having a director class is not strictly necessary
– Might be a good place to put various construction routines for reuse
– Completely hiding the details of construction from the client code
– director 定义执行构建步骤的顺序,而构建器提供具体的实现
– 拥有一个 director 类并不是绝对必要的
– 可能是放置各种构建例程以供重用的好地方
– 在客户端代码中完全隐藏构建细节

Builder: Implementation

  1. Clearly define the common construction steps for building all available product representations
  2. Declare these steps in the base builder interface
  3. Create a concrete builder class for each of the product representations and implement their construction steps, and also implement a method for fetching the result of construction
  4. Consider creating a director class (not necessarily)
  5. The client code creates both the builder and the director objects
  6. The construction result can be obtained directly from the director only if all products follow the same interface; otherwise, the client should fetch the result from the builder

1.明确定义构建所有可用产品表示的常见构建步骤
2.在 base builder 界面中声明这些步骤
3.为每个产品表示创建一个具体的 builder 类并实现它们的构造步骤,并实现一个获取构造结果的方法
4.考虑创建一个 director 类(不一定)
5.客户端代码会同时创建 builder 和 director 对象
6.只有当所有产品都遵循相同的接口时,才能直接从 director 获得构造结果;否则,客户端应从生成器中获取结果

Prototype: Problem and Solution

Problem: creating an exact copy of an object
问题:创建对象的精确副本
– Some fields may not be visible from the outside
– The code becomes dependent on that class
– Sometimes you only know the interface but not the concrete class
– 某些字段可能从外部不可见
– 代码变得依赖于该类
– 有时您只知道接口,而不知道具体的类

Solution: the Prototype pattern
– Delegating the cloning process to the actual objects being cloned
– A common interface for all objects supporting cloning, with a singleclone method
– An object supporting cloning is called a prototype
– 将克隆过程委托给正在克隆的实际对象
– 支持克隆的所有对象的通用接口,具有单个
– 支持克隆的对象称为原型

Prototype: Example

Produce exact copies of geometric objects, without coupling the code to their classes
生成几何对象的精确副本,而无需将代码耦合到其类

Note: a subclass may call the parent’s cloning method before copying its own field values to the resulting object.
注意:子类可以调用父级的克隆方法将自己的 Field 值复制到结果对象中。

posted @ 2024-10-24 21:05  Mephostopheles  阅读(9)  评论(0编辑  收藏  举报