命令模式通过将请求封装为对象,实现调用者与接收者的解耦。示例中定义了Command接口及LightOnCommand、LightOffCommand具体实现,RemoteControl作为调用者通过Execute方法间接控制Light状态,输出“Light is on”和“Light is off”,支持扩展撤销、队列等功能。

在Go语言中,命令模式是一种行为设计模式,它将请求封装为对象,从而使你可以用不同的请求、队列或日志来参数化其他对象。命令模式也支持可撤销的操作。下面通过一个简单的示例展示如何在Golang中实现命令模式的请求封装与执行。
定义命令接口
首先定义一个统一的命令接口,所有具体命令都实现该接口的 Execute 方法。
type Command interface { Execute()}
实现具体命令
假设我们有一个电灯(Light)设备,可以通过打开和关闭命令来控制。先定义设备:
type Light struct { state string}func (l *Light) TurnOn() { l.state = "on" fmt.Println("Light is on")}func (l *Light) TurnOff() { l.state = "off" fmt.Println("Light is off")}
接着创建两个具体命令:打开灯和关闭灯。
立即学习“go语言免费学习笔记(深入)”;
type LightOnCommand struct { light *Light}func (c *LightOnCommand) Execute() { c.light.TurnOn()}type LightOffCommand struct { light *Light}func (c *LightOffCommand) Execute() { c.light.TurnOff()}
使用命令调用者(Invoker)
调用者不直接操作设备,而是持有命令对象并执行它。
type RemoteControl struct { command Command}func (r *RemoteControl) PressButton() { if r.command != nil { r.command.Execute() }}
完整示例演示
将所有部分组合起来,演示命令的封装与执行:
package mainimport "fmt"// Command 接口type Command interface { Execute()}// 接收者:灯type Light struct { state string}func (l *Light) TurnOn() { l.state = "on" fmt.Println("Light is on")}func (l *Light) TurnOff() { l.state = "off" fmt.Println("Light is off")}// 具体命令:开灯type LightOnCommand struct { light *Light}func (c *LightOnCommand) Execute() { c.light.TurnOn()}// 具体命令:关灯type LightOffCommand struct { light *Light}func (c *LightOffCommand) Execute() { c.light.TurnOff()}// 调用者type RemoteControl struct { command Command}func (r *RemoteControl) PressButton() { if r.command != nil { r.command.Execute() }}// 示例使用func main() { light := &Light{} onCommand := &LightOnCommand{light: light} offCommand := &LightOffCommand{light: light} remote := &RemoteControl{} // 执行开灯命令 remote.command = onCommand remote.PressButton() // 执行关灯命令 remote.command = offCommand remote.PressButton()}
输出结果:
Light is onLight is off
通过这种方式,调用者(RemoteControl)与接收者(Light)完全解耦。你可以轻松替换命令,实现宏命令(组合多个命令)、撤销操作(添加 Undo 方法)或命令队列等功能。
基本上就这些,命令模式在任务调度、操作记录、UI按钮等场景中非常实用。结构清晰,扩展性强。
以上就是Golang命令模式请求封装与执行示例的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1404205.html
微信扫一扫
支付宝扫一扫