适配器模式(对象适配器、类适配器):
将一个类的接口转换成客户希望的另一个接口。适配器模式让那些接口不兼容的类可以一起工作。
适配者即被适配的角色,它定义了一个已经存在的接口,这个接口需要适配,适配者类包好了客户希望的业务方法。
对象适配器:
interface Target{ public function MethodOne(); public function MethodTwo(); } class Adaptee{ public function MethodOne(){ echo "+++++++++\n"; } } class Adapter implements Target{ private $adaptee; public function __construct(Adaptee $adaptee){ $this->adaptee = $adaptee; } public function MethodOne(){ $this->adaptee->MethodOne(); } public function MethodTwo(){ echo "------------"; } } $adaptee = new Adaptee(); $adapter = new Adapter($adaptee); $adapter->MethodOne();
类适配器:
class Adapter2 extends Adaptee implements Target{ public function MethodTwo(){ echo "-----------"; } } $adapter2 = new Adapter2(); $adapter2->MethodOne();