定義一系列演算法,封裝各自邏輯並使其可互換,演算法變化獨立於使用它的客戶端。
<?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());
Illuminate\Cache\Repository 策略模式實作。