-
Notifications
You must be signed in to change notification settings - Fork 24
/
command.go
76 lines (60 loc) · 1.48 KB
/
command.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
package command
import "fmt"
////////////////////////////////
//这里使用军训的例子,使用队列向左转,向右转,向后转的口令
//命令发出者是教官,命令执行者是队列
//ICommand 命令接口,队列要进行响应
type ICommand interface {
Execute()
}
//Troop 队列
type Troop struct{ name string }
//Execute cmd
func (t *Troop) Execute() {
fmt.Println("cmd had been executed by", t.name)
}
//TurnLeftCommand 向左转
type TurnLeftCommand struct {
//可以携带参数,每个命令有一个接收者,去执行
receiver ICommand
}
//Execute 执行向左转
func (t *TurnLeftCommand) Execute() {
fmt.Print("Troop Turn Left\n")
t.receiver.Execute()
}
//TurnRightCommand 向右转
type TurnRightCommand struct {
//可以携带参数
receiver ICommand
}
//Execute 执行向右转
func (t *TurnRightCommand) Execute() {
fmt.Print("Troop Turn Right\n")
t.receiver.Execute()
}
//TurnBackCommand 向后转
type TurnBackCommand struct {
//可以携带参数
holdTime int //保持时间
receiver ICommand
}
//Execute 执行向后转
func (t *TurnBackCommand) Execute() {
fmt.Print("Troop Turn Back\n")
t.receiver.Execute()
}
// Instructor 教官
type Instructor struct {
commands []ICommand
}
//AddCommand 教官喊口令一般都是一连串
func (i *Instructor) AddCommand(c ICommand) {
i.commands = append(i.commands, c)
}
//Execute 教官的Execute是发出命令
func (i *Instructor) Execute() {
for _, cmd := range i.commands {
cmd.Execute()
}
}