PHP設計模式(七)適配器模式(Adapter For PHP)

來源:互聯網
上載者:User

標籤:相容   翻頁   adapter   電子   對象   相關   協同   style   alt   

適配器模式:將一個類的介面轉換成客戶希望的另外一個介面,使得原本由於介面不相容而不能一起工作的那些類可以在一起工作。

如(借圖): 

 

 // 設定書的介面

// 書介面interface BookInterface{    // 翻頁方法    public function turnPage();    // 開啟書方法    public function open();}

 

// 紙質書實作類別class Book implements BookInterface{    public function turnPage()    {        echo "紙質書翻頁". "<br>";    }    public function open()    {        echo "紙質書開啟". "<br>";    }}

用戶端測試:

// 用戶端測試$book = new Book();$book->open();$book->turnPage();

輸出結果:

紙質書開啟紙質書翻頁

 

這時候,你想建立一個可以複用的類,該類可以與其他不相關的類或不可預見的類(即那些介面可能不一定相容的類)協同工作。

如下:

// 待適配對象class Kindle{    public function turnPage()    {        echo "電子書翻頁". "<br>";    }    public function open()    {        echo "電子書開啟". "<br>";    }}

 

// 適配器

class KindleAdapter implements BookInterface{    protected $_kindle;    public function __construct($obj)    {        $this->_kindle = $obj;    }    public function turnPage()    {        $this->_kindle->turnPage();    }    public function open()    {        $this->_kindle->open();    }}

 

// 用戶端測試

$kindle = new KindleAdapter(new Kindle());$kindle->open();$kindle->turnPage();

// 輸出結果

電子書開啟電子書翻頁

 

 

後記:

本文僅為個人學習筆記整理,如有紕漏之處,歡迎指正!

 

PHP設計模式(七)適配器模式(Adapter For PHP)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.