go-pattern-examples/behavior/11_command/command.go

77 lines
1.5 KiB
Go
Raw Normal View History

2020-04-21 17:50:21 +03:00
package command
import "fmt"
2020-05-05 17:03:44 +03:00
////////////////////////////////
//这里使用军训的例子,使用队列向左转,向右转,向后转的口令
//命令发出者是教官,命令执行者是队列
//ICommand 命令接口,队列要进行响应
type ICommand interface {
2020-04-21 17:50:21 +03:00
Execute()
}
2020-05-05 17:03:44 +03:00
//Troop 队列
type Troop struct{ name string }
2020-04-21 17:50:21 +03:00
2020-05-05 17:03:44 +03:00
//Execute cmd
func (t *Troop) Execute() {
fmt.Println("cmd had been executed by", t.name)
2020-04-21 17:50:21 +03:00
}
2020-05-05 17:03:44 +03:00
//TurnLeftCommand 向左转
type TurnLeftCommand struct {
//可以携带参数,每个命令有一个接收者,去执行
receiver ICommand
2020-04-21 17:50:21 +03:00
}
2020-05-05 17:03:44 +03:00
//Execute 执行向左转
func (t *TurnLeftCommand) Execute() {
fmt.Print("Troop Turn Left\n")
t.receiver.Execute()
2020-04-21 17:50:21 +03:00
}
2020-05-05 17:03:44 +03:00
//TurnRightCommand 向右转
type TurnRightCommand struct {
//可以携带参数
receiver ICommand
2020-04-21 17:50:21 +03:00
}
2020-05-05 17:03:44 +03:00
//Execute 执行向右转
func (t *TurnRightCommand) Execute() {
fmt.Print("Troop Turn Right\n")
t.receiver.Execute()
2020-04-21 17:50:21 +03:00
}
2020-05-05 17:03:44 +03:00
//TurnBackCommand 向后转
type TurnBackCommand struct {
//可以携带参数
holdTime int //保持时间
receiver ICommand
2020-04-21 17:50:21 +03:00
}
2020-05-05 17:03:44 +03:00
//Execute 执行向后转
func (t *TurnBackCommand) Execute() {
fmt.Print("Troop Turn Back\n")
t.receiver.Execute()
2020-04-21 17:50:21 +03:00
}
2020-05-05 17:03:44 +03:00
// Instructor 教官
type Instructor struct {
commands []ICommand
2020-04-21 17:50:21 +03:00
}
2020-05-05 17:03:44 +03:00
//AddCommand 教官喊口令一般都是一连串
func (i *Instructor) AddCommand(c ICommand) {
i.commands = append(i.commands, c)
2020-04-21 17:50:21 +03:00
}
2020-05-05 17:03:44 +03:00
//Execute 教官的Execute是发出命令
func (i *Instructor) Execute() {
for _, cmd := range i.commands {
cmd.Execute()
}
2020-04-21 17:50:21 +03:00
}