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

1 <?php
2 /**
3 * 装饰模式
4 *
5 * 动态的给一个对象添加一些额外的职责,就扩展功能而言比生成子类方式更为灵活
6 */
7 header("Content-type:text/html;charset=utf-8");
8 abstractclass MessageBoardHandler
9 {
10 publicfunction __construct(){}
11 abstractpublicfunction filter($msg);
12 }
13
14 class MessageBoard extends MessageBoardHandler
15 {
16 publicfunction filter($msg)
17 {
18 return"处理留言板上的内容|".$msg;
19 }
20 }
21
22 $obj=new MessageBoard();
23 echo$obj->filter("一定要学好装饰模式<br/>");
24
25 // --- 以下是使用装饰模式 ----
26 class MessageBoardDecorator extends MessageBoardHandler
27 {
28 private$_handler=null;
29
30 publicfunction __construct($handler)
31 {
32 parent::__construct();
33 $this->_handler =$handler;
34 }
35
36 publicfunction filter($msg)
37 {
38 return$this->_handler->filter($msg);
39 }
40 }
41
42 // 过滤html
43 class HtmlFilter extends MessageBoardDecorator
44 {
45 publicfunction __construct($handler)
46 {
47 parent::__construct($handler);
48 }
49
50 publicfunction filter($msg)
51 {
52 return"过滤掉HTML标签|".parent::filter($msg);; // 过滤掉HTML标签的处理 这时只是加个文字 没有进行处理
53 }
54 }
55
56 // 过滤敏感词
57 class SensitiveFilter extends MessageBoardDecorator
58 {
59 publicfunction __construct($handler)
60 {
61 parent::__construct($handler);
62 }
63
64 publicfunction filter($msg)
65 {
66 return"过滤掉敏感词|".parent::filter($msg); // 过滤掉敏感词的处理 这时只是加个文字 没有进行处理
67 }
68 }
69
70 $obj=new HtmlFilter(new SensitiveFilter(new MessageBoard()));
71 echo$obj->filter("一定要学好装饰模式!<br/>");

posted on 2011-01-04 23:18  bluefrog  阅读(1656)  评论(0编辑  收藏  举报