[php]php设计模式 State (状态模式)

1 <?php
2 /**
3 * 状态模式
4 *
5 * 允许一个对象在其内部状态改变时改变它的行为,对象看起来似乎修改了它所属的类
6 *
7 */
8 interface State
9 {
10 publicfunction handle($state);
11 publicfunction display();
12 }
13
14 class Context
15 {
16 private$_state=null;
17
18 publicfunction __construct($state)
19 {
20 $this->setState($state);
21 }
22
23 publicfunction setState($state)
24 {
25 $this->_state =$state;
26 }
27
28 publicfunction request()
29 {
30 $this->_state->display();
31 $this->_state->handle($this);
32 }
33 }
34
35 class StateA implements State
36 {
37 publicfunction handle($context)
38 {
39 $context->setState(new StateB());
40 }
41
42 publicfunction display()
43 {
44 echo"state A<br/>";
45 }
46 }
47
48 class StateB implements State
49 {
50 publicfunction handle($context)
51 {
52 $context->setState(new StateC());
53 }
54
55 publicfunction display()
56 {
57 echo"state B<br/>";
58 }
59 }
60
61 class StateC implements State
62 {
63 publicfunction handle($context)
64 {
65 $context->setState(new StateA());
66 }
67
68 publicfunction display()
69 {
70 echo"state C<br/>";
71 }
72 }
73
74 // 实例化一下
75 $objContext=new Context(new StateB());
76 $objContext->request();
77 $objContext->request();
78 $objContext->request();
79 $objContext->request();
80 $objContext->request();

posted on 2011-06-21 00:08  bluefrog  阅读(1302)  评论(0编辑  收藏  举报