1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace State
7 {
8 class Work
9 {
10 private State state;
11 public Work()
12 {
13 this.state =
new ForenoonState();
14 }
15
16 private double hour;
17 public double Hour
18 {
19 get {
return hour; }
20 set { hour =
value; }
21 }
22
23 public void SetState(State s)
24 {
25 this.state =
s;
26 }
27 //为了调用state的行为
28 public void WriteProgram()
29 {
30 state.WriteProgram(
this);
31 }
32 }
33 abstract class State
34 {
35 public abstract void WriteProgram(Work w);
36 }
37 class ForenoonState : State
38 {
39 public override void WriteProgram(Work w)
40 {
41 if (w.Hour <
12)
42 {
43 Console.WriteLine(
"当前时间上午{0}点,精神百倍!",w.Hour);
44 }
45 else
46 {
47 w.SetState(
new NoonState());
48 w.WriteProgram();
49 }
50 }
51 }
52 class NoonState : State
53 {
54 public override void WriteProgram(Work w)
55 {
56 if (w.Hour <
14)
57 {
58 Console.WriteLine(
"当前时间中午午{0}点,想睡觉!",w.Hour);
59 }
60 else
61 {
62 w.SetState(
new AfternoonState());
63 w.WriteProgram();
64 }
65 }
66 }
67 class AfternoonState : State
68 {
69 public override void WriteProgram(Work w)
70 {
71 if (w.Hour <
18)
72 {
73 Console.WriteLine(
"当前时间中午午{0}点,快下班了!", w.Hour);
74 }
75 else
76 {
77 w.SetState(
new SleepingState());
78 w.WriteProgram();
79 }
80 }
81 }
82 class SleepingState : State
83 {
84 public override void WriteProgram(Work w)
85 {
86 Console.WriteLine(
"当前时间中午午{0}点,睡着了!", w.Hour);
87 }
88 }
89 class Program
90 {
91 static void Main(
string[] args)
92 {
93 Work w =
new Work();
94 w.Hour =
9;
95 w.WriteProgram();
96 w.Hour =
13;
97 w.WriteProgram();
98 w.Hour =
17;
99 w.WriteProgram();
100 w.Hour =
23;
101 w.WriteProgram();
102 }
103 }
104 }
转载于:https://www.cnblogs.com/CheeseZH/archive/2012/05/21/2512206.html
转载请注明原文地址: https://win8.8miu.com/read-1494489.html