PHP設計模式之適配器模式代碼執行個體

來源:互聯網
上載者:User

   這篇文章主要介紹了PHP設計模式之適配器模式代碼執行個體,本文講解了目標、角色、應用情境、優勢等內容,並給出代碼執行個體,需要的朋友可以參考下

  目標:

  可將一個類的介面轉換成客戶希望的另外一個介面,使得原本不相容的介面能夠一起工作。通俗的理解就是將不同介面適配成統一的API介面。

  角色:

  Target適配目標,該角色定義把其他類轉換為何種介面,也就是我們的期望介面。

  Adaptee被適配者,就是需要被適配的介面。

  Adapter適配器,其他的兩個角色都是已經存在的角色,而適配器角色是需要建立立的,它用來對Adaptee與Target介面進行適配。

  應用情境:

  如資料操作有mysql、mysqli、pdo、sqlite、postgresql等,假若產生環境需要更換資料庫時,可利用適配器模式統一介面。同理cache的情境也是,這會是更換緩衝策略(memcache、redis、apc)更方便。

  優勢:

  被適配者通過適配器完成對適配目標的適配,以達到對客戶使用透明的目的。

  範例程式碼:

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 //適配目標,規定的介面將被適配對象實現 interface IDatabase { public function connect($host, $username, $password, $database); public function query($sql); }   //適配器 class Mysql implements IDatabase { protected $connect;   public function connect($host, $username, $password, $database) { $connect = mysql_connect($host, $username, $password); mysql_select_db($database, $connect); $this->connect = $connect; //... }   public function query($sql) { //... } }   //適配器 class Postgresql implements IDatabase { protected $connect;   public function connect($host, $username, $password, $database) { $this->connect = pg_connect("host=$host dbname=$database user=$username password=$password"); //... }   public function query($sql) { //... } }     //用戶端使用 $client = new Postgresql(); $client->query($sql);

  如上:

  Target適配目標: IDataBase介面

  Adaptee被適配者: mysql和postgresql的資料庫操作函數

  Adapter適配器 :mysql類和postgresql類

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.