PHP設計模式–適配器模式

來源:互聯網
上載者:User

適配器設計模式只是將某個對象的介面適配為另一個對象所期望的介面。

適配器設計模式的目標是有助於物件導向的代碼,該模式可以為對象介面建立回話。

通過執行個體說明:

 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對象不僅是最佳的做法,而且也能減少很多麻煩。

聯繫我們

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