What is a decorator
Decorator mode is used to adjust part of the content or functions of existing objects without modifying the original object structure. You can use decorator settings
Application scenarios
Design a UserInfo class with a UserInfo array inside to store username information
Add username via addUser
The getUserList method will print out the username information
Now we need to change the added user information to uppercase. We need not to change the original class and the original data structure
We designed a UserInfoDecorate class to complete this required operation, just like decoration, decorating the original data
The decorator pattern is somewhat like the adapter pattern, but it must be noted that the decorator is mainly a prerequisite for not changing the existing object data structure
Code: UserInfo
[php]
//Decorator mode is used to adjust part of the content or functions of existing objects without modifying the original object structure. You can use the decorator design mode
class UserInfo {
Public $userInfo = array();
Public function addUser($userInfo) {
$this->userInfo[] = $userInfo;
}
Public function getUserList() {
print_r($this->userInfo);
}
}
Code: UserInfoDecorate has the same decoration, changing the user information output to uppercase format without changing the original UserInfo class
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();
http://www.bkjia.com/PHPjc/478144.html