命令模式在Golang中通过接口和组合实现解耦,核心角色包括Command、ConcreteCommand、Receiver、Invoker和Client;示例以遥控器控制电灯展示开/关命令及扩展撤销功能,适用于参数化操作、队列执行、撤销重做与日志回放等场景。

在Golang中实现命令模式,可以将请求封装为独立对象,使发送者与接收者解耦。这种设计让操作可参数化、排队、记录日志或支持撤销。下面通过一个简单的示例说明如何用Go语言实现命令模式。
命令模式通常包含以下角色:
假设我们要实现一个遥控器控制电灯开关的功能:
<span style="color: #008000">// 接收者:电灯</span>
type Light struct{}
func (l *Light) On() {
fmt.Println("电灯已打开")
}
func (l *Light) Off() {
fmt.Println("电灯已关闭")
}
<span style="color: #008000">// 命令接口</span>
type Command interface {
Execute()
}
<span style="color: #008000">// 具体命令:开灯命令</span>
type LightOnCommand struct {
light *Light
}
func (c *LightOnCommand) Execute() {
c.light.On()
}
<span style="color: #008000">// 具体命令:关灯命令</span>
type LightOffCommand struct {
light *Light
}
func (c *LightOffCommand) Execute() {
c.light.Off()
}
<span style="color: #008000">// 调用者:遥控器</span>
type RemoteControl struct {
command Command
}
func (r *RemoteControl) PressButton() {
r.command.Execute()
}
客户端使用方式:
立即学习“go语言免费学习笔记(深入)”;
func main() {
light := &Light{}
onCommand := &LightOnCommand{light: light}
offCommand := &LightOffCommand{light: light}
remote := &RemoteControl{}
remote.command = onCommand
remote.PressButton() // 输出:电灯已打开
remote.command = offCommand
remote.PressButton() // 输出:电灯已关闭
}
命令模式的优势在于易于扩展。例如添加撤销功能:
<span style="color: #008000">// 扩展命令接口支持撤销</span>
type UndoableCommand interface {
Command
Undo()
}
func (c *LightOnCommand) Undo() {
c.light.Off()
}
func (c *LightOffCommand) Undo() {
c.light.On()
}
此时调用者也可记录历史命令,实现批量撤销:
type RemoteControlWithUndo struct {
command Command
history []UndoableCommand
}
func (r *RemoteControlWithUndo) PressButton() {
if cmd, ok := r.command.(UndoableCommand); ok {
cmd.Execute()
r.history = append(r.history, cmd)
}
}
func (r *RemoteControlWithUndo) Undo() {
if len(r.history) == 0 {
return
}
last := r.history[len(r.history)-1]
last.Undo()
r.history = r.history[:len(r.history)-1]
}
命令模式适合以下场景:
在Go中虽然没有类继承,但通过接口和组合能优雅实现命令模式。关键是将“动作”封装成对象,降低调用者与具体逻辑的耦合。
基本上就这些,不复杂但容易忽略细节。
以上就是如何在Golang中实现命令模式封装请求_Golang命令模式应用示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号