首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 設計模式:建造者模式 實作範例

     編輯:PHP 綜合知識

模式定義

將複雜物件的建構過程與其表示分離,使相同的建構過程可建立不同表示。

應用場景

  • 物件建構步驟固定,但各步驟參數多變。
  • 需建立不同配置的同類物件(如不同規格的產品)。

程式碼實作

<?php
/** 產品類別:包含多個屬性 */
class Product {
    public $_type = null;
    public $_size = null;
    public $_color = null;

    public function setType($type) { echo "set product type
"; $this->_type = $type; } public function setSize($size) { echo "set product size
"; $this->_size = $size; } public function setColor($color) { echo "set product color
"; $this->_color = $color; } } /** 建造者:封裝建構邏輯 */ class ProductBuilder { private $_config = null; private $_object = null; public function __construct($config) { $this->_object = new Product(); $this->_config = $config; } public function build() { echo "--- in builder---
"; $this->_object->setType($this->_config['type']); $this->_object->setSize($this->_config['size']); $this->_object->setColor($this->_config['color']); } public function getProduct() { return $this->_object; } } /* 使用範例 */ $config = ['type' => 'shirt', 'size' => 'xl', 'color' => 'red']; // 無建造者:呼叫端需知道建構順序 $oProduct = new Product(); $oProduct->setType($config['type']); $oProduct->setSize($config['size']); $oProduct->setColor($config['color']); // 使用建造者:建構邏輯集中,呼叫端簡潔 $objBuilder = new ProductBuilder($config); $objBuilder->build(); $objProduct = $objBuilder->getProduct();

關鍵角色

  • Product:最終產生的複雜物件。
  • Builder (ProductBuilder):定義建構步驟,組裝零件。
  • Director(隱含):此範例中由呼叫端直接決定建構順序,複雜場景可抽離 Director 類別。

與工廠模式差異

工廠模式關注「建立什麼物件」,建造者模式關注「如何一步步建構物件」。建造者適合建構過程複雜、參數多變的情況。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved