1. 程式人生 > >設計模式學習系列——適配器模式

設計模式學習系列——適配器模式

參考 bool AD hide aps 一個 php display true

適配器模式

  適配器模式(Adapter Pattern),是將一種接口改造成另外一種接口的一個包裝類。

  適用場景:系統需要使用現有的類,但是此類的接口不符合系統的需要。

  優點: 1.提高了類的復用;2.增加了類的透明度;3靈活性好。

  缺點:使用太多,會顯得系統淩亂,增加系統的復雜度。適配器不會在系統設計的時候添加,一般只是用在對現有系統進行改進的時候使用。

  角色:

  1)目標接口

  2)適配器類

  3)適配者類

  4)使用者

考慮以下場景,筆記本是5V電源(假設是5V),需要連一個220v的電源,這個時候需要個適配器。參考以下代碼:

技術分享圖片
  1 <?php
  2
/* 3 * 適配器方法模式示例 4 */ 5 error_reporting(E_ALL); 6 ini_set(‘display_errors‘,‘on‘); 7 8 9 /* 10 * 角色:目標接口 11 * 接口類——電源 12 */ 13 interface Source{ 14 public function output($EAVoltage); 15 } 16 /* 17 * 角色;適配者類 18 * 實現類——220V電源 19 */ 20 class Source220V implements Source{ 21
const VOLTAGE = "220V"; 22 public function output($EAVoltage){ 23 if($EAVoltage == self::VOLTAGE){ 24 return self::VOLTAGE; 25 }else{ 26 return ""; 27 } 28 } 29 public function getVoltage(){ 30 return self::VOLTAGE; 31 }
32 } 33 34 /* 35 * 角色;適配者類 36 * 實現類——5V電源 37 */ 38 class Source5V implements Source{ 39 const VOLTAGE = "5V"; 40 public function output($EAVoltage){ 41 if($EAVoltage == self::VOLTAGE){ 42 return self::VOLTAGE; 43 }else{ 44 return false; 45 } 46 } 47 public function getVoltage(){ 48 return self::VOLTAGE; 49 } 50 } 51 52 /* 53 * 接口類——適配器 54 */ 55 interface Adapter { 56 public function input(Source $source); 57 public function output($EAVoltage); 58 } 59 60 /* 61 * 角色;適配器(組合方式) 62 * 實現類——220V轉5V 63 * 實現了適配器 64 */ 65 class Adapter220V implements Source{ 66 private $source; 67 68 public function output($EAVoltage){ 69 if($EAVoltage == "220V"){ 70 $this->source = new Source220V(); 71 return $this->source->output("220V"); 72 } 73 if($EAVoltage == "5V"){ 74 $this->source = new Source5V(); 75 return $this->source->output("5V"); 76 } 77 return false; 78 } 79 } 80 81 /* 82 * 角色;使用類 83 * 筆記本 84 */ 85 class NoteBook { 86 const VOLTAGE = "5V"; 87 /* 88 * 開機 89 */ 90 public function powerOn(){ 91 $source = new Adapter220V(); 92 if($source->output(self::VOLTAGE) == self::VOLTAGE){//采用output方法無需關註實現細節 93 return true; 94 }else{ 95 return false; 96 } 97 } 98 } 99 100 $noteBook = new NoteBook; 101 var_dump($noteBook->powerOn());//bool(true)
View Code

  

設計模式學習系列——適配器模式