這篇文章主要介紹了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類