Home > Backend Development > PHP Tutorial > PHP Design Pattern Series - Decorator_PHP Tutorial

PHP Design Pattern Series - Decorator_PHP Tutorial

WBOY
Release: 2016-07-13 17:52:13
Original
965 people have browsed it

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

[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();

Author: initphp

http://www.bkjia.com/PHPjc/478144.html

truehttp: //www.bkjia.com/PHPjc/478144.htmlTechArticleWhat is the decorator decorator mode, which adjusts some content or functions of existing objects, but does not require modification Original object structure, you can use decorators to design application scenarios...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template