原型模式 透過複製現有原型實例建立新物件,適用於:初始化昂貴 (資料庫查詢、檔案解析、複雜計算)、類別動態決定、避免子類別爆炸。PHP 原生 clone 關鍵字支援淺層複製,配合 __clone() 魔術方法可實作深層複製。
clone() 方法 (PHP 直接用關鍵字)。__clone 深層複製資源)。getPrototype(name) 回傳複製品。<?php
// 產品介面
interface UnitPrototype {
public function __clone(): void;
public function setOwner(int $playerId): void;
public function getInfo(): string;
}
// 具體原型:機槍兵
class Marine implements UnitPrototype {
public int $playerId;
private array $stats; // 基礎屬性 (共享不變)
private string $modelData; // 模型資料 (大型資源,需深層複製)
public function __construct(int $playerId) {
$this->playerId = $playerId;
// 模擬昂貴初始化:載入模型、動畫、音效...
$this->modelData = $this->loadHeavyModelData();
$this->stats = ['hp'=>40, 'dmg'=>6, 'range'=>5, 'speed'=>2.25];
echo "🔧 Marine 原型初始化 (載入模型資源) for Player {$playerId}
";
}
private function loadHeavyModelData(): string {
// 模擬讀取 2MB 模型檔
return str_repeat('model_data_', 20000);
}
// 深層複製:大型資源需重新複製或引用計數
public function __clone(): void {
// modelData 若為不可變資源可共享 (引用計數),若可變需深層複製
// 這裡示範深層複製 (實務上大資源常用共享 + copy-on-write)
$this->modelData = $this->modelData; // 字串複製 (PHP copy-on-write)
echo "📋 Marine 複製完成 (深層複製模型資料)
";
}
public function setOwner(int $playerId): void {
$this->playerId = $playerId;
}
public function getInfo(): string {
return "Marine[P{$this->playerId}] HP:{$this->stats['hp']} DMG:{$this->stats['dmg']}";
}
}
// 坦克原型 (另一種單位)
class Tank implements UnitPrototype {
public int $playerId;
private array $stats;
private string $modelData;
private bool $siegeMode = false;
public function __construct(int $playerId) {
$this->playerId = $playerId;
$this->modelData = $this->loadHeavyModelData();
$this->stats = ['hp'=>150, 'dmg'=>30, 'range'=>7, 'speed'=>1.13];
echo "🔧 Tank 原型初始化 for Player {$playerId}
";
}
private function loadHeavyModelData(): string {
return str_repeat('tank_model_', 50000); // 更大
}
public function __clone(): void {
$this->modelData = $this->modelData;
$this->siegeMode = false; // 複製時重置狀態
echo "📋 Tank 複製完成
";
}
public function setOwner(int $playerId): void { $this->playerId = $playerId; }
public function getInfo(): string { return "Tank[P{$this->playerId}] HP:{$this->stats['hp']} Siege:{$this->siegeMode}"; }
public function toggleSiege(): void { $this->siegeMode = !$this->siegeMode; }
}
// 原型管理器
class UnitPrototypeRegistry {
private array $prototypes = [];
public function register(string $name, UnitPrototype $prototype): void {
$this->prototypes[$name] = $prototype;
}
public function getPrototype(string $name): UnitPrototype {
if (!isset($this->prototypes[$name])) {
throw new InvalidArgumentException("原型不存在: {$name}");
}
return clone $this->prototypes[$name];
}
public function has(string $name): bool {
return isset($this->prototypes[$name]);
}
}
// 客戶端使用
$registry = new UnitPrototypeRegistry();
// 註冊基礎原型 (每陣營一個)
$registry->register('marine_p1', new Marine(1));
$registry->register('marine_p2', new Marine(2));
$registry->register('tank_p1', new Tank(1));
$registry->register('tank_p2', new Tank(2));
echo "
大量生產單位:
";
// 玩家 1 生產 10 隻機槍兵
for ($i = 0; $i < 10; $i++) {
$marine = $registry->getPrototype('marine_p1');
// 可微調屬性 (如升級)
// $marine->upgradeWeapon();
echo $marine->getInfo() . "
";
}
echo "
";
// 玩家 2 生產 5 輛坦克
for ($i = 0; $i < 5; $i++) {
$tank = $registry->getPrototype('tank_p2');
echo $tank->getInfo() . "
";
}
?>
<?php
class Shallow {
public array $data = [1,2,3];
public StdClass $obj;
public function __construct() {
$this->obj = new StdClass();
$this->obj->val = 'original';
}
}
$orig = new Shallow();
$clone = clone $orig;
// 淺層複製:陣列與物件屬性仍指向同一記憶體
$clone->data[] = 4;
$clone->obj->val = 'cloned';
var_dump($orig->data); // [1,2,3] 陣列被複製 (PHP copy-on-write)
var_dump($orig->obj->val); // 'cloned' 物件未複製!共享同一實例
// 深層複製需在 __clone 手動處理
class Deep extends Shallow {
public function __clone() {
$this->obj = clone $this->obj; // 遞迴複製物件屬性
// 陣列自動 copy-on-write,通常無需手動處理
}
}
?>
| 模式 | 建立方式 | 適用場景 |
|---|---|---|
| 原型 | 複製現有實例 | 初始化昂貴、類別動態、狀態複雜、避免子類別爆炸 |
| 建造者 | 分步驟建構 | 建構流程固定、零件多變、參數多 |
| 工廠方法 | 子類別決定實例化 | 單一物件、邏輯封裝、解耦具體類別 |
<?php
// 服務容器支援原型作用域 (每次取得新複製品)
$container->prototype(HeavyService::class, function() {
$proto = new HeavyService(); // 昂貴初始化
return fn() => clone $proto; // 回傳複製器
});
// 使用
$svc1 = $container->get(HeavyService::class); // clone
$svc2 = $container->get(HeavyService::class); // clone
?>
原型模式將「建立邏輯」封裝在原型物件內,客戶端只需知道名稱即可獲得新實例,降低耦合並提升效能。