【设计模式】20、command 命令模式

本文详细介绍了Go语言中的Command模式,通过button和device之间的命令接口,实现了延迟执行和远程控制。通过例子展示了如何使用onButton和offButton结构体以及onCommand和offCommand命令接口来操作device对象。
摘要由CSDN通过智能技术生成

二十、command 命令模式

在 client 和 object 之间增加一个 command 层, 可以延迟执行 或 远程执行

20.1 button_command_device

├── button.go
├── button_test.go
├── command.go
└── device.go

20.1.1 button_test.go

package _01button_command_device

import (
	"github.com/stretchr/testify/require"
	"testing"
)

/*
=== RUN   TestButton
--- PASS: TestButton (0.00s)
PASS
*/
func TestButton(t *testing.T) {
	d := &tv{isOn: false}
	require.False(t, d.isOn)
	var b button = &onButton{command: &onCommand{device: d}}
	b.press()
	require.True(t, d.isOn)

	b = &offButton{command: &offCommand{device: d}}
	require.True(t, d.isOn)
	b.press()
	require.False(t, d.isOn)
}

20.1.2 button.go

package _01button_command_device

type button interface {
	press()
}

type onButton struct {
	command Command
}

func (b *onButton) press() {
	b.command.execute()
}

type offButton struct {
	command Command
}

func (b *offButton) press() {
	b.command.execute()
}

20.1.3 command.go

package _01button_command_device

type Command interface {
	execute()
}

type onCommand struct {
	device device
}

func (c *onCommand) execute() {
	c.device.On()
}

type offCommand struct {
	device device
}

func (c *offCommand) execute() {
	c.device.Off()
}

20.1.4 device.go

package _01button_command_device

type device interface {
	On()
	Off()
}
type tv struct {
	isOn bool
}

func (d *tv) On() {
	d.isOn = true
}

func (d *tv) Off() {
	d.isOn = false
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

呆呆的猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值