PHP設計模式系列 - 裝飾器_PHP教程

來源:互聯網
上載者:User
什麼是裝飾器
裝飾器模式,對已有對象的部分內容或者功能進行調整,但是不需要修改原始對象結構,可以使用裝飾器設
應用情境
設計一個UserInfo類,裡面有UserInfo數組,用於儲存使用者名稱資訊
通過addUser來添加使用者名稱
getUserList方法將列印出使用者名稱資訊
現在需要將添加的使用者資訊變成大寫的,我們需要不改變原先的類,並且不改變原先的資料結構
我們設計了一個UserInfoDecorate類來完成這個需求的操作,就像裝飾一樣,給原先的資料進行了裝修
裝飾器模式有些像適配器模式,但是一定要注意,裝飾器主要是不改變現有對象資料結構的前提
代碼:UserInfo
[php]
//裝飾器模式,對已有對象的部分內容或者功能進行調整,但是不需要修改原始對象結構,可以使用裝飾器設計模式
class UserInfo {

public $userInfo = array();

public function addUser($userInfo) {
$this->userInfo[] = $userInfo;
}

public function getUserList() {
print_r($this->userInfo);
}
}

代碼:UserInfoDecorate 裝飾一樣,改變使用者資訊輸出為大寫格式,不改變原先UserInfo類
[php]
include("UserInfo.php");
class UserInfoDecorate {

public function makeCaps($UserInfo) {
foreach ($UserInfo->userInfo as &$val) {
$val = strtoupper($val);
}
}

}

$UserInfo = new UserInfo;
$UserInfo->addUser('zhu');
$UserInfo->addUser('initphp');
$UserInfoDecorate = new UserInfoDecorate;
$UserInfoDecorate->makeCaps($UserInfo);
$UserInfo->getUserList();

作者:initphp

http://www.bkjia.com/PHPjc/478144.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/478144.htmlTechArticle什麼是裝飾器 裝飾器模式,對已有對象的部分內容或者功能進行調整,但是不需要修改原始對象結構,可以使用裝飾器設 應用情境 設計一...

  • 聯繫我們

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