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/>");

相关文章

解析func_num_args与func_get_args函数的使用

func_num_args函数功能– 返回传递到函数的参数数目,其语法如下 : int func_num_args (void )。说明 : 返回传递到目前定义函数的参数数目。如果是从函...

PHP基础知识介绍

php中的整形数是有符号的,不能表示无符号整数,当整形数超出范围时,会自动从整形数转化成float数,可以用php_int_size常量来查看php整数类型所占字节,一般为4个字节,所以...

使用apache模块rewrite_module (转)

把 [url]http://wwww.aaaaaaaaa.com/... 的地址形式改为 [url]http://wwww.aaaaaaaaa.com/... 或者 [url]http:...

iis下php mail函数的sendmail配置方法(官方推荐)

首先你需要先到从http://glob.com.au/sendmail/下载sendmail.zip文件,点此可以直接下载噢,然后把它解压到如D:\php\sendmail\目录下。 然...

PHP实现搜索时记住状态的方法示例

本文实例讲述了PHP实现搜索时记住状态的方法。分享给大家供大家参考,具体如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Tra...