PHP design mode Decorator (decoration mode)

高洛峰
Release: 2023-03-01 10:18:02
Original
1193 people have browsed it

Copy the code The code is as follows:
/**
* Decoration mode
*
* Dynamically add some additional responsibilities to an object, which is more flexible than generating subclasses in terms of extended functionality
*/
header("Content-type:text/html;charset=utf-8");
abstract class MessageBoardHandler
{
public function __construct (){}
abstract public function filter($msg);
}

class MessageBoard extends MessageBoardHandler
{
public function filter($msg)
{
return "Processing the content on the message board|".$msg;
}
}

$obj = new MessageBoard();
echo $obj->filter("Be sure to learn the decoration mode
");

// --- The following is how to use the decoration mode- ---
class MessageBoardDecorator extends MessageBoardHandler
{
private $_handler = null;

public function __construct($handler)
{
parent::__construct();
$this->_handler = $handler;
}

public function filter($msg)
{
return $this->_handler->filter($msg);
}
}

// Filter html
class HtmlFilter extends MessageBoardDecorator
{
public function __construct($ handler)
{
parent::__construct($handler);
}

public function filter($msg)
{
return "Filter out HTML tags|".parent::filter($msg);; // Filter The process of removing HTML tags is just to add text without processing
}
}

// Filter sensitive words
class SensitiveFilter extends MessageBoardDecorator
{
public function __construct($handler)
{
parent::__construct($handler ; Processing
}
}

$obj = new HtmlFilter(new SensitiveFilter(new MessageBoard()));
echo $obj->filter("Be sure to learn the decoration mode!
");

Related labels:
php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!