每个Person都可以发送命令,每个命令对应着人和动作
package main
import "fmt"
// 每个Person都可以发送命令,每个命令对应着人和动作
// 如王五可以向李四发送听取指令的命令
// 李四可以向张三发送买东西的指令
type Person struct {
name string
cmd Command
}
type Command struct {
person *Person
method func()
}
func NewCommand(p *Person, method func()) Command {
return Command{
person: p,
method: method,
}
}
func (c *Command) Execute() {
if c.method == nil {
return
}
c.method()
}
func NewPerson(name string, cmd Command) Person {
return Person{
name: name,
cmd: cmd,
}
}
func (p *Person) Buy() {
fmt.Printf("%s is buying\n", p.name)
p.cmd.Execute()
}
func (p *Person) Cook() {
fmt.Printf("%s is cooking\n", p.name)
p.cmd.Execute()
}
func (p *Person) Wash() {
fmt.Printf("%s is washing\n", p.name)
p.cmd.Execute()
}
func (p *Person) Listen() {
fmt.Printf("%s is listening\n", p.name)
p.cmd.Execute()
}
func (p *Person) Talk() {
fmt.Printf("%s is talking\n", p.name)
p.cmd.Execute()
}
func main() {
zhangsan := NewPerson("张三", NewCommand(nil, nil))
lisi := NewPerson("李四", NewCommand(&zhangsan, zhangsan.Buy))
wangwu := NewPerson("王五", NewCommand(&lisi, lisi.Listen))
wangwu.Talk()
}
发表回复