建造者模式 適用於建構過程固定、但零件組合多變的場景。如星際爭霸關卡初始化:地圖地形、建築配置、部隊編制各自複雜,但組裝順序固定 (先地圖、再建築、最後部隊)。
getResult() 回傳最終產品。<?php
// 產品:遊戲場景
class GameScene {
public array $mapLayers = [];
public array $buildings = [];
public array $units = [];
public function __toString(): string {
return "場景: " . count($this->mapLayers) . " 地圖層, "
. count($this->buildings) . " 建築, "
. count($this->units) . " 單位";
}
}
// 建造者介面
interface SceneBuilder {
public function buildMap(): void;
public function buildBuildings(): void;
public function buildUnits(): void;
public function getResult(): GameScene;
}
// 具體建造者:任務關卡 1-1
class Mission1_1Builder implements SceneBuilder {
private GameScene $scene;
public function __construct() {
$this->scene = new GameScene();
}
public function buildMap(): void {
echo "🗺️ 建構地圖: 草原地形、兩座礦區、一條河流
";
$this->scene->mapLayers = ['terrain', 'minerals', 'river'];
}
public function buildBuildings(): void {
echo "🏗️ 放置建築: 指揮中心、兵營、補給站
";
$this->scene->buildings = ['command_center', 'barracks', 'supply_depot'];
}
public function buildUnits(): void {
echo "🪖 部署部隊: 3 機槍兵、1 醫療兵、2 SCV
";
$this->scene->units = ['marine','marine','marine','medic','scv','scv'];
}
public function getResult(): GameScene {
echo "🔧 組裝場景完成
";
return $this->scene;
}
}
// 指導者:控制建構流程
class MissionDirector {
public function __construct(private SceneBuilder $builder) {}
public function construct(): void {
$this->builder->buildMap();
$this->builder->buildBuildings();
$this->builder->buildUnits();
}
}
// 客戶端使用
$builder = new Mission1_1Builder();
$director = new MissionDirector($builder);
$director->construct();
$scene = $builder->getResult();
echo $scene; // 場景: 3 地圖層, 3 建築, 6 單位
?>
| 模式 | 核心意圖 | 適用場景 |
|---|---|---|
| 建造者 | 分步驟建構複雜物件,流程固定、零件多變 | SQL 查詢建構器、文檔產生器、遊戲場景、HTTP 請求建構 |
| 工廠方法 | 延遲實例化到子類別,單一物件建立 | 資料庫驅動、日誌處理器、支付閘道 |
| 抽象工廠 | 建立相關/依賴物件家族 | 跨平台 UI 組件、多資料庫適配器套件 |
| 原型 | 透過複製現有實例建立新物件 | 大量相似物件、初始化昂貴、狀態複雜 |
<?php
class QueryBuilder {
private array $parts = ['select' => '*', 'from' => '', 'where' => [], 'order' => ''];
public function select(string $columns): self { $this->parts['select'] = $columns; return $this; }
public function from(string $table): self { $this->parts['from'] = $table; return $this; }
public function where(string $col, $val): self { $this->parts['where'][] = "$col = ?"; $this->bindings[] = $val; return $this; }
public function orderBy(string $col, string $dir = 'ASC'): self { $this->parts['order'] = "$col $dir"; return $this; }
public function getSQL(): string {
$sql = "SELECT {$this->parts['select']} FROM {$this->parts['from']}";
if ($this->parts['where']) $sql .= " WHERE " . implode(' AND ', $this->parts['where']);
if ($this->parts['order']) $sql .= " ORDER BY {$this->parts['order']}";
return $sql;
}
}
// 使用
$sql = (new QueryBuilder())
->select('id, name, email')
->from('users')
->where('status', 'active')
->where('role', 'admin')
->orderBy('created_at', 'DESC')
->getSQL();
?>
建造者模式讓「建構流程」與「具體實作」分離,新增關卡類型只需新增 ConcreteBuilder,不修改 Director,符合開放封閉原則。