適配器設計模式只是將某個對象的介面適配為另一個對象所期望的介面。
適配器設計模式的目標是有助於物件導向的代碼,該模式可以為對象介面建立回話。
通過執行個體說明:
1 /* 2 在項目最初的程式碼程式庫中,名為errorObject的對象能夠處理所有錯誤的訊息和代碼。直接將訊息輸入至控制台: 3 */ 4 5 class errorObject{ 6 private $__error; 7 8 pubic function __construct($error){ 9 $this->__error = $error;10 }11 12 public function getError(){13 return $this->__error;14 }15 }16 17 class logToConsole{18 private $__errorObject;19 20 public function __construct($errorObject){21 $this->__errorObject = $errorObject;22 }23 24 public function write(){25 fwrite(STDERR,$this->__errorObject->getError());26 }27 }28 29 /*30 這樣在使用時只需要如下代碼:31 */32 33 $error = new errorObject("404:Not Found");34 35 $log = new logToConsole($error);36 37 $log->write();38 39 /*40 這時項目中加入了新的網路系統管理員,需要將錯誤記錄至一個多列CSV檔案,要求第一行是錯誤碼,第二行是錯誤文本。41 */42 class logToCSV{43 const CSV_LOCATION = 'log.csv';44 45 private $__errorObject;46 47 public function __construct($errorObject){48 $this->__errorObject = $errorObject;49 }50 51 public function write(){52 $line = $this->__errorObject->getErrorNumber();53 $line .= ',';54 $line .= $this->__errorObject->getErrorText();55 $line .="\n";56 57 file_put_contents(self::CSV_LOCATION,$line,FILE_APPEND);58 }59 }60 61 /*62 針對這個問題可以1.更改現有程式碼程式庫的errorObject類;2.建立一個Adapter對象。考慮到保持這些公用介面標準型的需求,建立一個Adapter對象是最佳的選擇。63 */64 65 class logToCSVAdapter extends errorObject66 {67 private $__errorNumber,$__errorText;68 69 public function __construct($error){70 parent::__construct($error);71 72 $parts = explode(':',$this->getError());73 74 $this->__errorNumber = $parts[0];75 76 $this->__errorText = $parts[1];77 } 78 79 public function getErrorNumber(){80 return $this->__errorNumber;81 }82 83 public function getErrorText(){84 return $this->__errorText;85 }86 }87 88 /*89 這樣,在使用時可以這樣調用:90 */91 92 $error = new logToCSVAdater("404:Not Found");93 94 $log = new logToCSV($error);95 96 $log->write();
在需要轉化一個對象的介面用於另一個對象時,實現Adapter對象不僅是最佳的做法,而且也能減少很多麻煩。