將複雜物件的建構過程與其表示分離,使相同的建構過程可建立不同表示。
<?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();
工廠模式關注「建立什麼物件」,建造者模式關注「如何一步步建構物件」。建造者適合建構過程複雜、參數多變的情況。