forked from go/golangs_learn
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
1.0 KiB
1.0 KiB
package command
import "fmt"
type Person struct {
name string
cmd Command
}
func NewPerson(name string, cmd Command) Person {
return Person{
name: name,
cmd: cmd,
}
}
type Command struct {
person *Person
method func()
}
func (c *Command) Exec() {
c.method()
}
func NewCommand(person *Person, method func()) Command {
return Command{
person: person,
method: method,
}
}
func (p *Person) Buy() {
if p != nil {
fmt.Printf("%s 正在Buy\n", p.name)
p.cmd.Exec()
}
}
func (p *Person) Sleep() {
if p != nil {
fmt.Printf("%s 正在Sleep\n", p.name)
p.cmd.Exec()
}
}
func (p *Person) Wash() {
if p != nil {
fmt.Printf("%s 正在Wash\n", p.name)
p.cmd.Exec()
}
}
func (p *Person) Drink() {
if p != nil {
fmt.Printf("%s 正在Drink\n", p.name)
p.cmd.Exec()
}
}
func (p *Person) Eat() {
if p != nil {
fmt.Printf("%s 正在Eat\n", p.name)
p.cmd.Exec()
}
}
-
命令模式
-
命令模式属于将函数作为属性操作,通过实例化结构体,调用属性函数,实现命令执行