php设计模式 Decorator(装饰模式)

Valentina ·
更新时间:2024-09-21
· 893 次阅读

代码如下:
<?php
/**
* 装饰模式
*
* 动态的给一个对象添加一些额外的职责,就扩展功能而言比生成子类方式更为灵活
*/
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 "处理留言板上的内容|".$msg;
}
}
$obj = new MessageBoard();
echo $obj->filter("一定要学好装饰模式<br/>");
// --- 以下是使用装饰模式 ----
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);
}
}
// 过滤html
class HtmlFilter extends MessageBoardDecorator
{
public function __construct($handler)
{
parent::__construct($handler);
}
public function filter($msg)
{
return "过滤掉HTML标签|".parent::filter($msg);; // 过滤掉HTML标签的处理 这时只是加个文字 没有进行处理
}
}
// 过滤敏感词
class SensitiveFilter extends MessageBoardDecorator
{
public function __construct($handler)
{
parent::__construct($handler);
}
public function filter($msg)
{
return "过滤掉敏感词|".parent::filter($msg); // 过滤掉敏感词的处理 这时只是加个文字 没有进行处理
}
}
$obj = new HtmlFilter(new SensitiveFilter(new MessageBoard()));
echo $obj->filter("一定要学好装饰模式!<br/>");
您可能感兴趣的文章:PHP设计模式之装饰者模式代码实例PHP设计模式之装饰者模式学习php设计模式 php实现装饰器模式(decorator)PHP面向对象程序设计组合模式与装饰模式详解PHP设计模式之装饰器模式定义与用法详解php适配器模式简单应用示例php桥接模式应用案例分析php 策略模式原理与应用深入理解php设计模式之工厂模式用法经典实例分析php设计模式之观察者模式定义与用法经典示例php设计模式之职责链模式定义与用法经典示例php装饰者模式简单应用案例分析



装饰模式 PHP

需要 登录 后方可回复, 如果你还没有账号请 注册新账号