[php]php设计模式 Chain Of Responsibility (职责链模式)

1 <?php
2 /**
3 * 职责链模式
4 *
5 * 为解除请求的发送者和接收者之间的耦合,而使用多个对象都用机会处理这个请求,将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它
6 *
7 */
8 abstractclass Handler
9 {
10 protected$_handler=null;
11
12 publicfunction setSuccessor($handler)
13 {
14 $this->_handler =$handler;
15 }
16
17 abstractfunction handleRequest($request);
18 }
19
20 class ConcreteHandlerZero extends Handler
21 {
22 publicfunction handleRequest($request)
23 {
24 if($request==0)
25 {
26 echo"0<br/>";
27 } else {
28 $this->_handler->handleRequest($request);
29 }
30 }
31 }
32
33 class ConcreteHandlerOdd extends Handler
34 {
35 publicfunction handleRequest($request)
36 {
37 if($request%2)
38 {
39 echo$request." is odd<br/>";
40 } else {
41 $this->_handler->handleRequest($request);
42 }
43 }
44 }
45
46 class ConcreteHandlerEven extends Handler
47 {
48 publicfunction handleRequest($request)
49 {
50 if(!($request%2))
51 {
52 echo$request." is even<br/>";
53 } else {
54 $this->_handler->handleRequest($request);
55 }
56 }
57 }
58
59
60 // 实例一下
61 $objZeroHander=new ConcreteHandlerZero();
62 $objEvenHander=new ConcreteHandlerEven();
63 $objOddHander=new ConcreteHandlerOdd();
64 $objZeroHander->setSuccessor($objEvenHander);
65 $objEvenHander->setSuccessor($objOddHander);
66
67 foreach(array(2,3,4,5,0) as$row)
68 {
69 $objZeroHander->handleRequest($row);
70 }

posted on 2011-06-22 23:26  bluefrog  阅读(1216)  评论(0编辑  收藏  举报