適配器模式(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();