适配器模式(Adapter):将一个类的接口转换成客户但愿的另一个接口。Adapter 模式使得本来因为接口不兼容而不能一块儿工做的那些类能够一块儿工做。php
类适配器:this
/** * Target.php(目标接口) * Interface Target */ interface Target { public function method1(); public function method2(); } /** * Adaptee.php(源接口) * Class Adaptee */ class Adaptee { public function method1() { echo "Adaptee Method1<br/>\n"; } } /** * Adapter.php(适配器) * Class Adapter */ class Adapter extends Adaptee implements Target { public function method2() { // TODO: Implement method2() method. echo "Adapter Method2<br/>\n"; } } // 客户端调用 $adapter = new Adapter(); $adapter->method1(); $adapter->method2();
对象适配器:spa
/** * Target.php(目标接口) * Interface Target */ interface Target { public function method1(); public function method2(); } /** * Adaptee.php(源接口) * Class Adaptee */ class Adaptee { public function method1() { echo "Adaptee Method1<br/>\n"; } } /** * Adapter.php(适配器) * Class Adapter */ class Adapter implements Target { private $adaptee; public function __construct(Adaptee $adaptee) { $this->adaptee = $adaptee; } public function method1() { // TODO: Implement method1() method. $this->adaptee->method1(); } public function method2() { // TODO: Implement method2() method. echo "Adapter Method2<br/>\n"; } } // 客户端调用 $adapter = new Adapter(new Adaptee()); $adapter->method1(); $adapter->method2();