创建文件Command.go
package command type Command interface { Execute() // 执行 }
创建文件motherBoard.go
package command import "fmt" type MotherBoard struct { } func (*MotherBoard) WashClothes() { fmt.Println("MM去洗衣服") } func (*MotherBoard) WarmBed() { fmt.Println("MM去暖床") }
创建文件MMCommand1.go
package command type MMCommand1 struct { mb *MotherBoard } func NewMMCommand1(mb *MotherBoard) *MMCommand1 { return &MMCommand1{mb: mb} } func (mmc1 *MMCommand1) Execute() { mmc1.mb.WashClothes() // 洗衣服 }
创建文件MMCommand2.go
package command type MMCommand2 struct { mb *MotherBoard } func NewMMCommand2(mb *MotherBoard) *MMCommand2 { return &MMCommand2{mb: mb} } func (mmc1 *MMCommand2) Execute() { mmc1.mb.WarmBed() }
创建文件Box.go
package command import "fmt" type Box struct { WashClothes Command WarmBed Command } func NewBox(washClothes, warmBed Command) *Box { return &Box{ WashClothes: washClothes, WarmBed: warmBed, } } func (b *Box) GoWashClothes() { fmt.Println("给妹子买了一束花") b.WashClothes.Execute() } func (b *Box) GoWarmBed() { fmt.Println("给妹子买了iPhone") b.WarmBed.Execute() }
main.go
package main import "test/design/command" func main() { mb := &command.MotherBoard{} cm1 := command.NewMMCommand1(mb) cm2 := command.NewMMCommand2(mb) box1 := command.NewBox(cm1, cm2) box1.GoWarmBed() box1.GoWashClothes() box2 := command.NewBox(cm1, cm2) box2.GoWarmBed() box2.GoWashClothes() }