命令模式通过将请求封装为对象,实现调用者与接收者的解耦。示例中定义了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()
}
调用者不直接操作设备,而是持有命令对象并执行它。
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按钮等场景中非常实用。结构清晰,扩展性强。
以上就是Golang命令模式请求封装与执行示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号