萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 享元模式實作:遊戲單位圖像共享降低記憶體

享元模式:共享內在狀態,外部化外在狀態

享元模式 適用於大量相似物件場景:將不變的「內在狀態」(圖像、動畫、模型) 共享,將變化的「外在狀態」(座標、血量、陣營顏色) 外部傳入。星際爭霸上百單位同屏時,共享模型資源可大幅降低記憶體佔用。

核心概念

  • 內在狀態:可共享、不隨環境改變 (圖像資源、動畫幀、聲音、基本屬性)。
  • 外在狀態:隨環境改變、不可共享 (座標、朝向、當前血量、玩家顏色)。
  • 享元工廠:管理享元池,確保相同內在狀態只建立一個實例。

星際單位享元實作

<?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) . " 隻機槍兵
"; ?>

享元模式 vs 單例 vs 物件池

模式核心目的實例數量狀態管理
享元共享內在狀態,減少記憶體每類型 1 個 (或少量變體)內在共享、外在外部傳入
單例全域唯一存取點整個應用 1 個全域狀態
物件池重用昂貴物件實例,避免頻繁建構/銷毀池大小可配置完整狀態重置後重用

PHP 實務應用場景

  • 文字編輯器字元:每個字元字型、大小、樣式共享,位置、顏色外部化。
  • 地圖瓦片/地形:相同地形圖片共享,座標外部化。
  • 資料庫連線池:連線物件重用 (較接近物件池)。
  • 大量相似 DTO/實體:共享元資料定義,實例只攜帶資料值。

注意事項

  • 執行緒安全:PHP 單執行緒無此問題,但若用 Swoole/RoadRunner 多進程需注意共享記憶體。
  • 外在狀態傳遞成本:若外在狀態龐大或頻繁建立陣列,可能抵銷記憶體優勢。
  • 過早優化:只有在確認有大量同類物件且記憶體確為瓶頸時才引入。
copyright © 萬盛學電腦網 all rights reserved