Maison >développement back-end >tutoriel php >每日一模式之php的适配器模式
/*** 适配器模式 :将某一个对象的接口适配为另外一个 */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();//适配器模式说的是同源,处理后适用不同的对象//如果不做适配处理可能会影响以前的功能,或者会任意添加方法,类的功能不再单一,不方便以后的扩张
适配器模式 :将某一个对象的接口适配为另外一个 ,可以用于同源但是需要不同的处理情况