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); } } //---- class HtmlFilter extends MessageBoardDecorator { public function __construct($handler) { parent::__construct($handler); } public function filter($msg) { return "过滤掉HTML标签|".parent::filter($msg); } } class SensitiveFilter extends MessageBoardDecorator { public function __construct($handler) { parent::__construct($handler); } public function filter($msg) { return "过滤掉HTML|".parent::filter($msg);// 过滤掉敏感词的处理这时只是加个文字没有进行处理 } } $obj = new HtmlFilter(new SensitiveFilter(new MessageBoard())); echo $obj->filter("一定学好装饰模式<br/>");