/** * 適配器模式 :將某一個對象的接口適配爲另一個 */ interface Seller{ public function sell(); } //場景:中草藥,直接買,特別處理後賣掉 class HerbalMedicine { private $_medicine,$_pick_date,$_keep_time; public function __construct($medicine){ $this->_medicine = $medicine; } public function getMedicne(){ return $this->_medicine; } //and so on } //直接出售 class RedictMedicineSeller implements Seller{ private $_medicine; public function __construct($medicine_obj){ $this->_medicine = $medicine_obj; } public function sell(){ echo $this->_medicine->getMedicne()." redict sell \n"; } } $herbarl_obj = new HerbalMedicine("中草藥"); $redict_obj = new RedictMedicineSeller($herbarl_obj); $redict_obj->sell(); //提取這個動做可能不單單是ExtractMedicineSeller 用到 //不能用ExtractMedicineSeller 的方法代替提取 class HerbalMedicineAdapter extends HerbalMedicine{ public function __construct($medicine){ parent::__construct($medicine); $this->extract($medicine); } public function extract(){ echo "extract medicine \n"; } } //好比提取出青蒿素處理後出售 class ExtractMedicineSeller implements Seller{ private $_medicine; public function __construct($medicine_obj){ $this->_medicine = $medicine_obj; } public function sell(){ echo $this->_medicine->getMedicne()." extract sell \n"; } } $herbarl_adapter_obj = new HerbalMedicineAdapter("中草藥"); $extract_obj = new ExtractMedicineSeller($herbarl_adapter_obj); $extract_obj->sell(); //適配器模式說的是同源,處理後適用不一樣的對象 //若是不作適配處理可能會影響之前的功能,或者會任意添加方法,類的功能再也不單一,不方便之後的擴張
適配器模式 :將某一個對象的接口適配爲另一個 ,能夠用於同源可是須要不一樣的處理狀況php