首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 適配器模式詳解:類適配器與物件適配器實戰

     編輯:PHP 綜合知識

適配器模式將一個類的介面轉換成客戶端期望的另一個介面,讓原本不相容的類能夠合作。經典類比:牆上是兩孔插座(來源介面),電風扇需三孔插頭(目標介面),插座轉換器(適配器)橋接兩者。

三大核心角色

  • 目標角色:客戶端期望的介面
  • 來源角色:需被適配的既有介面
  • 適配器角色:核心元件,將來源介面轉換為目標介面

類適配器模式(繼承實作)

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();

兩種模式比較

維度類適配器物件適配器
實作方式多重繼承物件組合/委派
耦合度高(繼承為白箱復用)低(組合為黑箱復用)
靈活性靜態、編譯期決定動態、執行期可替換來源
推薦度一般不推薦✓ 推薦使用

物件適配器符合「組合優於繼承」原則,耦合度低、擴充性強,是實務開發的首選。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved