外觀模式 為子系統中的一組介面提供一個統一的高層介面,讓客戶端無需了解內部複雜結構即可使用。就像星際地圖編輯器:玩家只需滑鼠點擊,底層自動處理地形、單位、資源的繪製邏輯。
<?php
// 滑鼠狀態管理 (簡化的輸入模型)
class MouseState {
public static int $x = 0;
public static int $y = 0;
public static string $tool = 'ore'; // 當前選擇工具:ore, river, building...
}
// 子系統:水晶礦繪製
class OreDrawer {
public static function draw(int $x, int $y): void {
// 底層複雜繪圖邏輯:紋理貼圖、碰撞檢測、資源量初始化...
echo "在位置 ($x, $y) 繪製水晶礦
";
}
}
// 子系統:河流繪製
class RiverDrawer {
public static function draw(int $x, int $y): void {
echo "在位置 ($x, $y) 繪製河流段落
";
}
}
// 子系統:建築繪製
class BuildingDrawer {
public static function draw(int $x, int $y, string $type): void {
echo "在位置 ($x, $y) 建造 {$type}
";
}
}
// 外觀:地圖編輯器
class MapEditor {
public static function drawAtCursor(): void {
$x = MouseState::$x;
$y = MouseState::$y;
$tool = MouseState::$tool;
match ($tool) {
'ore' => OreDrawer::draw($x, $y),
'river' => RiverDrawer::draw($x, $y),
'barracks' => BuildingDrawer::draw($x, $y, '兵營'),
'factory' => BuildingDrawer::draw($x, $y, '工廠'),
default => echo "未知工具: {$tool}
",
}
}
// 批次操作:一鍵生成基地
public static function spawnBase(int $cx, int $cy): void {
BuildingDrawer::draw($cx, $cy, '指揮中心');
OreDrawer::draw($cx + 5, $cy + 3);
OreDrawer::draw($cx - 4, $cy + 6);
RiverDrawer::draw($cx + 10, $cy);
}
}
// 玩家操作流程
MouseState::$tool = 'ore';
MouseState::$x = 311;
MouseState::$y = 126;
MapEditor::drawAtCursor(); // 繪製單一水晶礦
// 一鍵生成基地
MapEditor::spawnBase(200, 200);
?>
| 模式 | 目的 | 關係 |
|---|---|---|
| 外觀 | 簡化介面,隱藏複雜度 | 單向:Facade → Subsystems |
| 適配器 | 轉換介面以符合預期契約 | 雙向:Client ↔ Adapter ↔ Adaptee |
| 中介者 | 集中管理物件間交互 | 多向:Colleagues ↔ Mediator |
Application::run() 內部初始化路由、資料庫、快取、事件派發器...PaymentGateway::charge() 內部處理多家支付商差異。外觀模式不禁止直接存取子系統,但提供「預設好用」的捷徑,降低認知負擔與耦合度。