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

相关文章

深入apache host的配置详解

<VirtualHost *:80>    ServerAdmin webmaster@dummy-host.127.0.0.1 &n...

php fread读取文件注意事项

php fread函数介绍 string fread ( int handle, int length ) fread() 从文件指针 handle 读取最多 length 个字节。...

php计算两个文件相对路径的方法

本文实例讲述了php计算两个文件相对路径的方法。分享给大家供大家参考。具体如下: 一、问题: 写一个php函数算出两个文件的相对路径。例如$a="/a/b/c/d/e.php"; $b=...

对Session和Cookie的区分与解释

对Session和Cookie的区分与理解  先说session 对SESSION的争论好象一直没有停止过,不过幺麽能理解SESSION的人应该占90以上。但还是讲讲,别嫌老~...

php urlencode()与urldecode()函数字符编码原理详解

php urlencode()与urldecode()函数字符编码原理详解

其原理就是把中文字符转换为十六进制并按某种规则进行字符串组合,实现字符的编码与解编码,保证URL数据传递过程中字符的完整性和兼容性,主要讨论中文字符的编码情况。 一,FireFox浏览器...