復制代碼 代碼如下:
 
<?php 
/** 
* 策略模式(Strategy.php) 
* 
* 定義一系列算法,把它們一個個封裝起來,并且使它們可相互替換,使用得算法的變化可獨立于使用它的客戶 
* 
*/ 
// ---以下是一系列算法的封閉---- 
interface CacheTable 
{ 
public function get($key); 
public function set($key,$value); 
public function del($key); 
} 
// 不使用緩存 
class NoCache implements CacheTable 
{ 
public function __construct(){ 
echo "Use NoCache<br/>"; 
} 
public function get($key) 
{ 
return false; 
} 
public function set($key,$value) 
{ 
return true; 
} 
public function del($key) 
{ 
return false; 
} 
} 
// 文件緩存 
class FileCache implements CacheTable 
{ 
public function __construct() 
{ 
echo "Use FileCache<br/>"; 
// 文件緩存構造函數(shù) 
} 
public function get($key) 
{ 
// 文件緩存的get方法實現(xiàn) 
} 
public function set($key,$value) 
{ 
// 文件緩存的set方法實現(xiàn) 
} 
public function del($key) 
{ 
// 文件緩存的del方法實現(xiàn) 
} 
} 
// TTServer 
class TTCache implements CacheTable 
{ 
public function __construct() 
{ 
echo "Use TTCache<br/>"; 
// TTServer緩存構造函數(shù) 
} 
public function get($key) 
{ 
// TTServer緩存的get方法實現(xiàn) 
} 
public function set($key,$value) 
{ 
// TTServer緩存的set方法實現(xiàn) 
} 
public function del($key) 
{ 
// TTServer緩存的del方法實現(xiàn) 
} 
} 
// -- 以下是使用不用緩存的策略 ------ 
class Model 
{ 
private $_cache; 
public function __construct() 
{ 
$this->_cache = new NoCache(); 
} 
public function setCache($cache) 
{ 
$this->_cache = $cache; 
} 
} 
class UserModel extends Model 
{ 
} 
class PorductModel extends Model 
{ 
public function __construct() 
{ 
$this->_cache = new TTCache(); 
} 
} 
// -- 實例一下 --- 
$mdlUser = new UserModel(); 
$mdlProduct = new PorductModel(); 
$mdlProduct->setCache(new FileCache()); // 改變緩存策略 
?> 
新聞熱點
疑難解答