1 <?php
2
3 /**
4 * 状态接口 (InterfaceState)
5 */
6 interface IState
7 {
8 function WriteCode(Work $w);
9 }
10
11
12
13 /**
14 * 上午工作状态
15 */
16 class AmState implements IState
17 {
18 public function WriteCode(Work $w)
19 {
20 if($w->_hour<=12)
21 {
22 echo "当前时间:{$w->_hour}点,上午工作;犯困,午休。<br/>";
23 }
24 else
25 {
26 $w->SetState(new PmState());
27 $w->WriteCode();
28 }
29 }
30 }
31
32 /**
33 * 下午工作状态
34 */
35 class PmState implements IState
36 {
37 public function WriteCode(Work $w)
38 {
39 if($w->_hour<=17)
40 {
41 echo "当前时间:{$w->_hour}点,下午工作状态还不错,继续努力。<br/>";
42 }
43 else
44 {
45 $w->SetState(new NightState());
46 $w->WriteCode();
47 }
48 }
49 }
50
51 /**
52 * 晚上工作状态
53 */
54 class NightState implements IState
55 {
56 public function WriteCode(Work $w)
57 {
58 if($w->IsDone)
59 {
60 $w->SetState(new BreakState());
61 $w->WriteCode();
62 }
63 else
64 {
65 if($w->_hour<=21)
66 {
67 echo "当前时间:{$w->_hour}点,加班哦,疲累至极。<br/>";
68 }
69 else
70 {
71 $w->SetState(new SleepState());
72 $w->WriteCode();
73 }
74 }
75 }
76 }
77
78 /**
79 * 休息状态
80 */
81 class BreakState implements IState
82 {
83 public function WriteCode(Work $w)
84 {
85 echo "当前时间:{$w->_hour}点,下班回家了。<br/>";
86 }
87 }
88
89 /**
90 * 睡眠状态
91 */
92 class SleepState implements IState
93 {
94 public function WriteCode(Work $w)
95 {
96 echo "当前时间:{$w->_hour}点,不行了,睡着了。<br/>";
97 }
98 }
99
100
101
102
103
104
105 /**
106 * 工作状态
107 */
108 class Work
109 {
110 private $_current;
111 public $_hour;
112 public $_isDone;
113
114 public function __construct()
115 {
116 $this->_current = new AmState();
117 }
118
119 public function SetState(IState $s)
120 {
121 $this->_current = $s;
122 }
123
124 public function WriteCode()
125 {
126 $this->_current->WriteCode($this);
127 }
128 }
129
130
131
132
133
134 //-------------------------状态模式-------------------------
135 $emergWork = new Work();
136
137 $emergWork->_hour = 9;
138 $emergWork->WriteCode();
139
140 $emergWork->_hour = 10;
141 $emergWork->WriteCode();
142
143 $emergWork->_hour = 13;
144 $emergWork->WriteCode();
145
146 $emergWork->_hour=14;
147 $emergWork->WriteCode();
148
149 $emergWork->_hour = 17;
150 $emergWork->WriteCode();
151
152 $emergWork->IsDone = true;
153 $emergWork->IsDone = false;
154
155 $emergWork->_hour = 19;
156 $emergWork->WriteCode();
157
158 $emergWork->_hour = 22;
159 $emergWork->WriteCode();
160
161
162
163
164
165
166 /*
167 当前时间:9点,上午工作;犯困,午休。
168 当前时间:10点,上午工作;犯困,午休。
169 当前时间:13点,下午工作状态还不错,继续努力。
170 当前时间:14点,下午工作状态还不错,继续努力。
171 当前时间:17点,下午工作状态还不错,继续努力。
172 当前时间:19点,加班哦,疲累至极。
173 当前时间:22点,不行了,睡着了。
174 */