"; } 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);}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",1);?>
适配器模式:将一个类(Oldcache)的接口转换成客户希望的另外一个接口(Cacheenable),使用原本不兼容的而不能在一起工作的那些类可以在一起工作。
通俗理解:亡羊补牢,需求变了,又添加功能了,又要重用之前的代码,怎么办?创建一个新类,对旧类进行封装,对方法进行重构,而不是去修改原来的类,达到适配新功能的效果。