首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 設計模式:策略模式 實作範例

     編輯:PHP 綜合知識

模式定義

定義一系列演算法,封裝各自邏輯並使其可互換,演算法變化獨立於使用它的客戶端。

程式碼實作

<?php
/** 策略介面:快取操作契約 */
interface CacheTable {
    public function get($key);
    public function set($key, $value);
    public function del($key);
}

/** 策略 A:不使用快取 */
class NoCache implements CacheTable {
    public function __construct() { echo "Use NoCache
"; } public function get($key) { return false; } public function set($key, $value) { return true; } public function del($key) { return false; } } /** 策略 B:檔案快取 */ class FileCache implements CacheTable { public function __construct() { echo "Use FileCache
"; } public function get($key) { /* 檔案讀取實作 */ } public function set($key, $value) { /* 檔案寫入實作 */ } public function del($key) { /* 檔案刪除實作 */ } } /** 策略 C:Tokyo Tyrant / TTServer */ class TTCache implements CacheTable { public function __construct() { echo "Use TTCache
"; } public function get($key) { /* TTServer 讀取 */ } public function set($key, $value) { /* TTServer 寫入 */ } public function del($key) { /* TTServer 刪除 */ } } /** 環境角色:持有策略並委派操作 */ class Model { private $_cache; public function __construct() { $this->_cache = new NoCache(); // 預設策略 } public function setCache(CacheTable $cache) { $this->_cache = $cache; } public function getData($key) { return $this->_cache->get($key); } } /* 使用範例 */ $userModel = new Model(); // 使用預設 NoCache $productModel = new Model(); $productModel->setCache(new TTCache()); // 切換為 TTCache // 執行期動態切換 $productModel->setCache(new FileCache());

關鍵角色

  • Strategy (CacheTable):演算法介面。
  • ConcreteStrategy (NoCache, FileCache, TTCache):具體演算法實作。
  • Context (Model):持有策略參考,提供統一介面給客戶端。

優點

  • 避免大量條件判斷(if/else/switch),新增策略不修改 Context。
  • 演算法邏輯隔離,易於測試與維護。
  • 執行期可動態切換策略(如依環境、使用者等級選擇快取)。

應用場景

  • 快取、日誌、驗證、排序、壓縮、路由演算法等可替換行為。
  • PHP 框架中常見:Illuminate\Cache\Repository 策略模式實作。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved