发布于 2014-11-09 05:54:10 | 208 次阅读 | 评论: 0 | 来源: 网友投递

本文为大家讲解的是php设计模式中的 Decorator(装饰模式)示例代码,感兴趣的同学参考下

动态的给一个对象添加一些额外的职责,就扩展功能而言比生成子类方式更为灵活


<?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/>");
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务