1、什麼是適配器模式?
適配器模式(Adapter)模式:將一個類的接口,轉換成客戶期望的另一個類的接口。適配器讓原本接口不兼容的類可以合作無間。
2、適配器模式中主要角色
目標(Target)角色:定義客戶端使用的與特定領域相關的接口,這也就是我們所期待得到的(電視,插孔是3個孔的)
源(Adaptee)角色:需要進行適配的接口(插孔是2個的)
適配器(Adapter)角色:對Adaptee的接口與Target接口進行適配;適配器是本模式的核心,適配器把源接口轉換成目標接口,此角色爲具體類。(插座)
3、具體代碼實現如下
1 <?php 2 3 // 目標角色,需要適配的 4 interface Target() 5 { 6 public function eat(); 7 } 8 9 // 源角色,已有的 10 class Adaptee 11 { 12 public function show() 13 { 14 echo 111; 15 } 16 } 17 18 // 適配器角色,實現源角色沒有的 19 class Adapter extends Adaptee implements Target 20 { 21 public function eat() 22 { 23 echo 222; 24 } 25 } 26 27 28 class Client 29 { 30 public function index() 31 { 32 $ad = new Adapter(); 33 $ad->show(); 34 $ad->eat(); 35 } 36 }