適配器模式將一個類的介面轉換成客戶端期望的另一個介面,讓原本不相容的類能夠合作。經典類比:牆上是兩孔插座(來源介面),電風扇需三孔插頭(目標介面),插座轉換器(適配器)橋接兩者。
interface Target {
public function sampleMethod1();
public function sampleMethod2();
}
class Adaptee {
public function sampleMethod1() { echo 'Adaptee sampleMethod1 <br />'; }
}
// 透過繼承 Adaptee 並實作 Target 介面
class Adapter extends Adaptee implements Target {
public function sampleMethod2() { echo 'Adapter sampleMethod2 <br />'; }
}
$adapter = new Adapter();
$adapter->sampleMethod1(); // 呼叫來源方法
$adapter->sampleMethod2(); // 呼叫適配新增方法
interface Target {
public function sampleMethod1();
public function sampleMethod2();
}
class Adaptee {
public function sampleMethod1() { echo 'Adaptee sampleMethod1 <br />'; }
}
// 透過組合持有 Adaptee 實例
class Adapter implements Target {
private $_adaptee;
public function __construct(Adaptee $adaptee) {
$this->_adaptee = $adaptee;
}
public function sampleMethod1() {
$this->_adaptee->sampleMethod1(); // 委派呼叫
}
public function sampleMethod2() { echo 'Adapter sampleMethod2 <br />'; }
}
$adaptee = new Adaptee();
$adapter = new Adapter($adaptee);
$adapter->sampleMethod1();
$adapter->sampleMethod2();
| 維度 | 類適配器 | 物件適配器 |
|---|---|---|
| 實作方式 | 多重繼承 | 物件組合/委派 |
| 耦合度 | 高(繼承為白箱復用) | 低(組合為黑箱復用) |
| 靈活性 | 靜態、編譯期決定 | 動態、執行期可替換來源 |
| 推薦度 | 一般不推薦 | ✓ 推薦使用 |
物件適配器符合「組合優於繼承」原則,耦合度低、擴充性強,是實務開發的首選。