學習高校課程-軟體設計模式-建造者模式和原型模式(lec4)

Mephostopheles發表於2024-10-24

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 值複製到結果物件中。

相關文章