1
0
Fork 0
design-patterns/go/command/main.go

138 lines
2.9 KiB
Go

package main
import "fmt"
/*
实例:
汤宝宝成为一国之王,手下有一个传令官和三个大臣,分别是内政大臣、外交大臣和军事大臣。
有一天,汤宝宝想要发布一个命令,传令官负责将命令传达给大臣们,大臣们根据命令的内容决定是否执行。
*/
// 接收者接口
type Receiver interface {
perform()
abort()
}
// 内政大臣
type HomeSecretary struct {
isPerforming bool
}
func (h *HomeSecretary) perform() {
h.isPerforming = true
fmt.Println("内政大臣开始执行命令")
}
func (h *HomeSecretary) abort() {
h.isPerforming = false
fmt.Println("内政大臣取消执行命令")
}
// 外交大臣
type ForeignSecretary struct {
isPerforming bool
}
func (f *ForeignSecretary) perform() {
f.isPerforming = true
fmt.Println("外交大臣开始执行命令")
}
func (f *ForeignSecretary) abort() {
f.isPerforming = false
fmt.Println("外交大臣取消执行命令")
}
// 军事大臣
type DefenseSecretary struct {
isPerforming bool
}
func (d *DefenseSecretary) perform() {
d.isPerforming = true
fmt.Println("军事大臣开始执行命令")
}
func (d *DefenseSecretary) abort() {
d.isPerforming = false
fmt.Println("军事大臣取消执行命令")
}
// 命令接口
type Command interface {
execute()
}
// 执行命令
type PerformCommand struct {
receiver Receiver
}
func (c *PerformCommand) execute() {
c.receiver.perform()
}
// 取消命令
type AbortCommand struct {
receiver Receiver
}
func (c *AbortCommand) execute() {
c.receiver.abort()
}
// Invoker - 传令官
type Herald struct {
commands []Command
}
func (h *Herald) addCommand(command Command) {
h.commands = append(h.commands, command)
}
func (h *Herald) executeCommands() {
for _, command := range h.commands {
command.execute()
}
h.commands = []Command{} // 清空命令列表
}
func main() {
fmt.Println("========= 命令模式 =========")
// 创建接收者
homeSecretary := &HomeSecretary{}
foreignSecretary := &ForeignSecretary{}
defenseSecretary := &DefenseSecretary{}
// 创建命令
performHomeCommand := &PerformCommand{receiver: homeSecretary}
abortHomeCommand := &AbortCommand{receiver: homeSecretary}
performForeignCommand := &PerformCommand{receiver: foreignSecretary}
abortForeignCommand := &AbortCommand{receiver: foreignSecretary}
performDefenseCommand := &PerformCommand{receiver: defenseSecretary}
abortDefenseCommand := &AbortCommand{receiver: defenseSecretary}
// 创建传令官
herald := &Herald{}
// 添加命令
herald.addCommand(performHomeCommand)
herald.addCommand(performForeignCommand)
herald.addCommand(performDefenseCommand)
// 执行命令
herald.executeCommands()
// 取消命令
herald.addCommand(abortHomeCommand)
herald.addCommand(abortForeignCommand)
herald.addCommand(abortDefenseCommand)
// 执行取消命令
herald.executeCommands()
fmt.Println()
fmt.Println("======= 命令模式结束 =======")
}