將一個類別的介面轉換成客戶端期望的另一個介面,使原本不相容的類別能夠合作。
<?php
/** 既有舊類別:介面不符合 Cacheable */
class OldCache {
public function __construct() { echo "OldCache construct
"; }
public function store($key, $value) { echo "OldCache store
"; }
public function remove($key) { echo "OldCache remove
"; }
public function fetch($key) { echo "OldCache fetch
"; }
}
/** 目標介面 */
interface Cacheable {
public function set($key, $value);
public function get($key);
public function del($key);
}
/** 適配器:實作目標介面,內部委派給 OldCache */
class OldCacheAdapter implements Cacheable {
private $_cache = null;
public function __construct() {
$this->_cache = new OldCache();
}
public function set($key, $value) {
return $this->_cache->store($key, $value);
}
public function get($key) {
return $this->_cache->fetch($key);
}
public function del($key) {
return $this->_cache->remove($key);
}
}
/* 使用範例 */
$objCache = new OldCacheAdapter();
$objCache->set('test', 1);
$objCache->get('test');
$objCache->del('test');