定義:
配接器模式(Adapter):將一個類的介面轉換成客戶希望的另外一個介面,Adapter 模式使得原本由于介面不兼容而不能一起作業的那些類可以一起作業,
結構:
- Target:目標介面,定義與客戶端互動相關的介面,目標可以是具體的或抽象的類,也可以是介面,
- Adaptee:源介面,需要適配的類,
- Adapter:配接器,對 Adaptee 的介面與 Target 介面進行適配,通過在內部包裝一個 Adaptee物件,把源介面轉換成目標介面,
- Client:客戶端代碼,
代碼實體:
類配接器:
/** * 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();
物件配接器:
/** * 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();
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/184385.html
標籤:設計模式
