文章目录
二十、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
}
本文详细介绍了Go语言中的Command模式,通过button和device之间的命令接口,实现了延迟执行和远程控制。通过例子展示了如何使用onButton和offButton结构体以及onCommand和offCommand命令接口来操作device对象。
821

被折叠的 条评论
为什么被折叠?



