-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommand.go
More file actions
75 lines (58 loc) · 1.11 KB
/
Command.go
File metadata and controls
75 lines (58 loc) · 1.11 KB
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
package main
import "fmt"
//很有用啊
type TV struct{}
func (tv *TV) On() {
fmt.Println("电视已打开")
}
func (tv *TV) Off() {
fmt.Println("电视已关闭")
}
type Command interface {
Execute()
Undo()
}
type OnCommand struct {
tv *TV
}
func (c *OnCommand) Execute() {
c.tv.On()
}
func (c *OnCommand) Undo() {
c.tv.Off()
}
type OffCommand struct {
tv *TV
}
func (c *OffCommand) Execute() {
c.tv.Off()
}
func (c *OffCommand) Undo() {
c.tv.On()
}
type RemoteControl struct {
history []Command
}
func (r *RemoteControl) Press(cmd Command) {
cmd.Execute()
r.history = append(r.history, cmd)
}
func (r *RemoteControl) PressUndo() {
if len(r.history) == 0 {
fmt.Println("没有命令可撤销")
return
}
last := r.history[len(r.history)-1]
last.Undo()
r.history = r.history[:len(r.history)-1]
}
func main() {
tv := &TV{}
onCmd := &OnCommand{tv}
offCmd := &OffCommand{tv}
remote := &RemoteControl{}
remote.Press(onCmd) // 输出:电视已打开
remote.Press(offCmd) // 输出:电视已关闭
remote.PressUndo() // 撤销:电视已打开
remote.PressUndo() // 撤销:电视已关闭
}