享元模式 適用於大量相似物件場景:將不變的「內在狀態」(圖像、動畫、模型) 共享,將變化的「外在狀態」(座標、血量、陣營顏色) 外部傳入。星際爭霸上百單位同屏時,共享模型資源可大幅降低記憶體佔用。
<?php
// 享元介面:定義繪製操作,接收外在狀態
interface UnitFlyweight {
public function render(array $extrinsicState): void;
}
// 具體享元:機槍兵圖像資源 (內在狀態)
class MarineFlyweight implements UnitFlyweight {
private string $modelPath;
private array $animations; // 共享動畫資源
public function __construct() {
// 模擬載入昂貴資源 (一次)
$this->modelPath = 'assets/units/marine.model';
$this->animations = [
'idle' => 'assets/anim/marine_idle.anim',
'attack' => 'assets/anim/marine_attack.anim',
'move' => 'assets/anim/marine_move.anim',
'death' => 'assets/anim/marine_death.anim',
];
echo "🔧 載入機槍兵模型與動畫資源 (僅一次)
";
}
public function render(array $extrinsicState): void {
// 實際繪製邏輯:結合內在資源 + 外在狀態
$x = $extrinsicState['x'];
$y = $extrinsicState['y'];
$playerColor = $extrinsicState['color'] ?? 'blue';
$hp = $extrinsicState['hp'] ?? 40;
$animation = $extrinsicState['animation'] ?? 'idle';
echo "🎨 繪製機槍兵 at ({$x},{$y}) 顏色:{$playerColor} HP:{$hp} 動作:{$animation}
";
// 實際會: 綁定模型、套用顏色著色器、播放動畫、繪製血條...
}
}
// 享元工廠:單例管理享元池
class FlyweightFactory {
private array $flyweights = [];
public function getFlyweight(string $unitType): UnitFlyweight {
if (!isset($this->flyweights[$unitType])) {
switch ($unitType) {
case 'marine':
$this->flyweights[$unitType] = new MarineFlyweight();
break;
case 'tank':
$this->flyweights[$unitType] = new TankFlyweight();
break;
case 'medic':
$this->flyweights[$unitType] = new MedicFlyweight();
break;
default:
throw new InvalidArgumentException("未知單位類型: {$unitType}");
}
}
return $this->flyweights[$unitType];
}
public function getCreatedCount(): int {
return count($this->flyweights);
}
}
// 其他單位享元 (略)
class TankFlyweight implements UnitFlyweight {
public function __construct() { echo "🔧 載入坦克模型資源
"; }
public function render(array $s): void { echo "🎨 繪製坦克 at ({$s['x']},{$s['y']})
"; }
}
class MedicFlyweight implements UnitFlyweight {
public function __construct() { echo "🔧 載入醫療兵模型資源
"; }
public function render(array $s): void { echo "🎨 繪製醫療兵 at ({$s['x']},{$s['y']})
"; }
}
// 客戶端:遊戲引擎渲染循環
$factory = new FlyweightFactory();
// 建立 100 隻機槍兵 (不同位置、顏色、血量)
$marines = [];
for ($i = 0; $i < 100; $i++) {
$marines[] = [
'type' => 'marine',
'x' => rand(0, 1000),
'y' => rand(0, 1000),
'color' => ['red','blue','green','yellow'][rand(0,3)],
'hp' => rand(10, 40),
'action' => ['idle','move','attack'][rand(0,2)],
];
}
// 渲染幀
echo "=== 開始渲染幀 ===
";
foreach ($marines as $m) {
$flyweight = $factory->getFlyweight($m['type']);
$flyweight->render($m); // 傳入外在狀態
}
echo "
總共建立享元實例: {$factory->getCreatedCount()} 個
"; // 1 個
echo "渲染了 " . count($marines) . " 隻機槍兵
";
?>
| 模式 | 核心目的 | 實例數量 | 狀態管理 |
|---|---|---|---|
| 享元 | 共享內在狀態,減少記憶體 | 每類型 1 個 (或少量變體) | 內在共享、外在外部傳入 |
| 單例 | 全域唯一存取點 | 整個應用 1 個 | 全域狀態 |
| 物件池 | 重用昂貴物件實例,避免頻繁建構/銷毀 | 池大小可配置 | 完整狀態重置後重用 |