-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path状态模式.cs
120 lines (113 loc) · 3.15 KB
/
状态模式.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
using System;
using Xunit;
namespace DesignMode
{
/// <summary>
/// 当一个对象的内在状态改变时允许改变其行为
/// 这个对象看起来像是改变了类
/// </summary>
public class 状态模式
{
[Fact]
public void Test()
{
//开启一个项目
Work work = new Work();
work.Hour = 9;
work.WriteProgram();
work.Hour = 10;
work.WriteProgram();
work.Hour = 13;
work.WriteProgram();
work.Hour = 19;
work.TaskFinished = false;
work.WriteProgram();
work.Hour = 21;
work.TaskFinished = true;
work.WriteProgram();
}
/// <summary>
/// 抽象状态
/// </summary>
abstract class State
{
public abstract void WriteProgram(Work work);
}
/// <summary>
/// 上午工作状态
/// </summary>
class ForenoonState : State
{
public override void WriteProgram(Work work)
{
if(work.Hour<12)
{
Console.WriteLine($"当前时间:{work.Hour} 上午工作状态");
}
else
{
//超过12点,则转入中午工作状态
work.SetState(new AfetrenoonState());
work.WriteProgram();
}
}
}
/// <summary>
/// 下午工作状态
/// </summary>
class AfetrenoonState : State
{
public override void WriteProgram(Work work)
{
if (work.Hour < 17)
{
Console.WriteLine($"当前时间:{work.Hour} 下午工作状态");
}
else
{
//超过17点,则转入晚上工作状态
work.SetState(new EveningState());
work.WriteProgram();
}
}
}
/// <summary>
/// 晚上工作状态
/// </summary>
class EveningState : State
{
public override void WriteProgram(Work work)
{
if(work.TaskFinished)
{
Console.WriteLine($"当前时间:{work.Hour} 工作完成 下班状态");
}
else
{
Console.WriteLine("额,继续完成工作...");
}
}
}
/// <summary>
/// 工作类
/// </summary>
class Work
{
public double Hour { get; set; }
public bool TaskFinished { get; set; }
private State _currentState;
public Work()
{
_currentState = new ForenoonState();
}
public void SetState(State state)
{
_currentState = state;
}
public void WriteProgram()
{
_currentState.WriteProgram(this);
}
}
}
}