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

yipeiwu_com6年前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实现的文件上传类与用法。分享给大家供大家参考,具体如下: FileUpload.class.php,其中用到了两个常量,可在网站配置文件中定义:define('ROO...

php字符串分割函数用法实例

本文实例讲述了php字符串分割函数用法。分享给大家供大家参考。具体分析如下: php中explode 和 split 函数用来分割字符串。 explode函数语法如下 explode...

PHP安装memcache扩展的步骤讲解

PHP安装memcache扩展的步骤讲解

PHP 5.6.23,查询目前最稳定的版本是memcache-2.2.7。 1.下载并解压缩。 wget http://pecl.php.net/get/memcache-2.2.7....

dirname(__FILE__)的含义和应用说明

__FILE__表示当前所在文件的绝对路径包括文件名,dirname(__FILE__)表示当前文件的绝对路径,basename(__FILE__)表示当前文件的文件名称,dirname...

php获取excel文件数据

很简单就可以实现,下面为大家简单介绍下 1、下载PHPExcel类,是一个文件夹,还得有一个文件PHPExcel.php,两个在同级目录 require __DIR__ . './P...