行为型 命令模式

为什么需要命令模式

命令模式主要是把命令函数封装成对象,这样可以方便存储、控制执行。主要应用场景是用来控制命令的执行,例如可以异步、延迟、排队执行命令、或者撤销重做命令、存储命令、记录命令。这样对于一个对象来说是很好实现的。

实现

实现上面就是在command里面注册操作所需对象,然后command类本身可以很轻松的被用户组合调用。

go.mod

module command

go 1.13

command.go

package command

import "fmt"

type Command interface {
	Execute()
}

type Device struct{}

type OnCommand struct {
	device *Device
}

func NewOnCommand(device *Device) *OnCommand {
	return &OnCommand{
		device: device,
	}
}

func (command *OnCommand) Execute() {
	fmt.Println("On")
}

type OffCommand struct {
	device *Device
}

func NewOffCommand(device *Device) *OffCommand {
	return &OffCommand{
		device: device,
	}
}

func (command *OffCommand) Execute() {
	fmt.Println("Off")
}

// Controller is a demo how we can use commands
type Controller struct {
	command1 Command
	command2 Command
}

func NewController(command1 Command, command2 Command) Controller {
	return Controller{
		command1: command1,
		command2: command2,
	}
}

func (controller Controller) TurnOn() {
	controller.command1.Execute()
}

func (controller Controller) TurnOff() {
	controller.command2.Execute()
}

command_test.go

package command_test

import (
	"command"
)

func ExampleCommand() {
	tv := &command.Device{}
	command1 := command.NewOnCommand(tv)
	command2 := command.NewOffCommand(tv)

	toyController := command.NewController(command1, command2)

	toyController.TurnOn()
	toyController.TurnOff()
	// output:
	// On
	// Off
}

执行: go test command -v

Previous
Next