-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathState.go
124 lines (99 loc) · 2.44 KB
/
State.go
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
121
package BehavioralType
import "fmt"
type TVState interface {
// 开机
PowerOn(r *RemoteControlMachine)
// 关机
PowerOff(r *RemoteControlMachine)
// 播放
Play(r *RemoteControlMachine)
// 待机
Standby(r *RemoteControlMachine)
}
// 待机状态
type StandByState struct {
r *RemoteControlMachine
}
func (s *StandByState) PowerOn(r *RemoteControlMachine) {}
func (s *StandByState) PowerOff(r *RemoteControlMachine) {
fmt.Println("关机")
// 使用遥控器设置电视机状态为关机
s.r = r
s.r.SetCurrentSate(&PowerOffState{})
// 执行关机
s.r.PowerOff()
}
func (s *StandByState) Play(r *RemoteControlMachine) {
fmt.Println("播放")
// 使用遥控器设置电视机状态为播放
s.r = r
s.r.SetCurrentSate(&PlayState{})
// 执行播放
s.r.Play()
}
func (s *StandByState) Standby(r *RemoteControlMachine) {
// do nothing
}
// 关机状态
type PowerOffState struct {
r *RemoteControlMachine
}
func (s *PowerOffState) PowerOn(r *RemoteControlMachine) {
fmt.Println("开机")
// 使用遥控器设置电视机状态为开机
s.r = r
s.r.SetCurrentSate(&StandByState{})
// 执行播放
s.r.Standby()
}
func (s *PowerOffState) PowerOff(r *RemoteControlMachine) {
}
func (s *PowerOffState) Play(r *RemoteControlMachine) {
}
func (s PowerOffState) Standby(r *RemoteControlMachine) {
}
// 播放状态
type PlayState struct {
r *RemoteControlMachine
}
func (s *PlayState) PowerOn(r *RemoteControlMachine) {}
func (s *PlayState) PowerOff(r *RemoteControlMachine) {
fmt.Println("关机")
// 使用遥控器设置电视机状态为关机
s.r = r
s.r.SetCurrentSate(&PowerOffState{})
// 执行关机
s.r.PowerOff()
}
func (s *PlayState) Play(r *RemoteControlMachine) {
}
func (s *PlayState) Standby(r *RemoteControlMachine) {
fmt.Println("开机")
// 使用遥控器设置电视机状态为开机
s.r = r
s.r.SetCurrentSate(&StandByState{})
// 执行播放
s.r.Standby()
}
// 引入控制器(上下文角色)
type RemoteControlMachine struct {
currentSate TVState
}
func (r *RemoteControlMachine) PowerOn() {
r.currentSate.PowerOn(r)
}
func (r *RemoteControlMachine) PowerOff() {
r.currentSate.PowerOff(r)
}
func (r *RemoteControlMachine) Play() {
r.currentSate.Play(r)
}
func (r *RemoteControlMachine) Standby() {
r.currentSate.Standby(r)
}
func (r *RemoteControlMachine) CurrentSate() TVState {
return r.currentSate
}
func (r *RemoteControlMachine) SetCurrentSate(currentSate TVState) {
r.currentSate = currentSate
}