跳转到主内容
趣航编程网 - 趣学编程,启航技术之路!

Golang命令模式请求封装与执行示例

命令模式通过将请求封装为对象,实现调用者与接收者的解耦。示例中定义了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) 调用者不直接操作设备,而是持有命令对象并执行它。 go语言参考手册 中文CHM版 Go 是一个开源的编程语言,它能让构造简单、可靠且高效的软件变得容易。本文给大家带来Go参考手册,需要的可以来下载! Go是从2007年末由Robert Griesemer, Rob Pike, Ken Thompson主持开发,后来还加入了Ian Lance Taylor, Russ Cox等人,并最终于2009年11月开源,在2012年早些时候发布了Go 1稳定版本。现在Go的开发已经是完全开放的,并且拥有一个活跃的社区。 Go 语言特色 简洁、快速、安全 并行、有趣、开源 内存管理、v数组安全、编译 下载
type RemoteControl struct { command Command } func (r *RemoteControl) PressButton() { if r.command != nil { r.command.Execute() } }
完整示例演示 将所有部分组合起来,演示命令的封装与执行:
package main import "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 on Light is off
通过这种方式,调用者(RemoteControl)与接收者(Light)完全解耦。你可以轻松替换命令,实现宏命令(组合多个命令)、撤销操作(添加 Undo 方法)或命令队列等功能。 基本上就这些,命令模式在任务调度、操作记录、UI按钮等场景中非常实用。结构清晰,扩展性强。

相关文章