将一个类的接口转换成兼容接口,使原本由于接口不兼容不能一起工作的类可以一起工作,通俗的讲:将已经存在的的类创建一个“中间类”,用户直接调用该中间类
四、代码示例
<?php /* * 适配器模式 */ /* * 类Cat和Dog已经存在,我们需要设计适配器类继承主类,对外开放统一调用 */ class Cat { public function eatfish() { return "Cat eat fish!"; } } class Dog { public function eatBone() { return "Dog eat Bone!"; } } /* * 设计适配器类 */ interface Adapter { public function Eat(); } class CatAdapter extends Cat implements Adapter { public function Eat() { return $this->eatfish(); } } class DogAdapter extends Dog implements Adapter { public function Eat() { return $this->eatBone(); } } /* * 主业务 */ class Animal { private $adapter; public function __construct($obj) { $this->adapter = $obj; } public function Eat() { return $this->adapter->Eat(); } } //小猫吃东西 $catObj = new CatAdapter(); $animal = new Animal($catObj); $animal->Eat(); //小狗吃东西 $dogObj = new DogAdapter(); $animal = new Animal($dogObj); $animal->Eat();