首页
读书
网课

正文

命令模式

命令模式本质是把某个对象的方法调用封装到对象中,方便传递、存储、调用。


示例中把主板单中的启动(start)方法和重启(reboot)方法封装为命令对象,再传递到主机(box)对象中。于两个按钮进行绑定:


第一个机箱(box1)设置按钮1(button1) 为开机按钮2(button2)为重启。

第二个机箱(box1)设置按钮2(button2) 为开机按钮1(button1)为重启。

从而得到配置灵活性。


除了配置灵活外,使用命令模式还可以用作:


批处理

任务队列

undo, redo

等把具体命令封装到对象中使用的场合


command.go

package command


import "fmt"


type Command interface {

    Execute()

}


type StartCommand struct {

    mb *MotherBoard

}


func NewStartCommand(mb *MotherBoard) *StartCommand {

    return &StartCommand{

        mb: mb,

    }

}


func (c *StartCommand) Execute() {

    c.mb.Start()

}


type RebootCommand struct {

    mb *MotherBoard

}


func NewRebootCommand(mb *MotherBoard) *RebootCommand {

    return &RebootCommand{

        mb: mb,

    }

}


func (c *RebootCommand) Execute() {

    c.mb.Reboot()

}


type MotherBoard struct{}


func (*MotherBoard) Start() {

    fmt.Print("system starting\n")

}


func (*MotherBoard) Reboot() {

    fmt.Print("system rebooting\n")

}


type Box struct {

    button1 Command

    button2 Command

}


func NewBox(button1, button2 Command) *Box {

    return &Box{

        button1: button1,

        button2: button2,

    }

}


func (b *Box) PressButton1() {

    b.button1.Execute()

}


func (b *Box) PressButton2() {

    b.button2.Execute()

}

command_test.go

package command


func ExampleCommand() {

    mb := &MotherBoard{}

    startCommand := NewStartCommand(mb)

    rebootCommand := NewRebootCommand(mb)


    box1 := NewBox(startCommand, rebootCommand)

    box1.PressButton1()

    box1.PressButton2()


    box2 := NewBox(rebootCommand, startCommand)

    box2.PressButton1()

    box2.PressButton2()

    // Output:

    // system starting

    // system rebooting

    // system rebooting

    // system starting

}



上一篇: 没有了
下一篇: 没有了
圣贤书院