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

yipeiwu_com5年前PHP代码库
复制代码 代码如下:

<?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 date_default_timezone_set('Asia/Shangha...

Opcache导致php-fpm崩溃nginx返回502

我这个博客为了提高运行效率在vps上装了opcache扩展,结果发现有个页面返回502,其他页面正常。 检查了php-fpm日志,发现是php-fpm子进程不知道为什么会崩溃,然后把op...

php面向对象 字段的声明与使用

字段是用于描述类的么个方面的性质。 字段是用于描述类的某个方面的性质。它与一般的PHP 变量非常相似,只是有一些细微的差别,本节将介绍这些差别。这一节还将讨论如何声明和使用字段,下一节则...

PHP重定向的3种方式

复制代码 代码如下://1header("Location: index.php"); //2echo '<scrīpt type="text/javascript">wi...

PHP5.2中PDO的简单使用方法

本文实例讲述了PHP5.2中PDO的简单使用方法。分享给大家供大家参考,具体如下: 一、PDO配置 1、确保PHP版本为5.2.5以上 2、在php.ini中找到Dynamic Exte...