命令模式通过将操作封装为对象实现请求与执行的解耦。在Go中利用接口和结构体可实现该模式:定义Command接口及Execute方法,Light作为接收者实现开灯关灯逻辑,LightOnCommand和LightOffCommand作为具体命令调用接收者方法,RemoteControl作为调用者触发命令执行,客户端组装并绑定对象。示例中遥控器按下按钮控制客厅灯的开关,输出“客厅 的灯打开了”和“客厅 的灯关闭了”。扩展Undo功能只需在接口增加Undo方法,具体命令实现反向操作,调用者维护历史记录以支持撤销。该模式适用于解耦发送者与接收者、支持日志、事务、撤销重做及宏命令组合场景。Go虽无类继承,但通过接口与组合仍能优雅实现命令模式,提升代码灵活性与可维护性。

命令模式是一种行为设计模式,它将请求封装为对象,从而使你可以用不同的请求、队列或日志来参数化其他对象。在 Golang 中,虽然没有类和继承的语法,但通过接口和结构体组合,依然可以优雅地实现命令模式。
命令模式的关键在于把“操作”变成一个可传递的对象。这样调用者(Invoker)不需要知道具体执行什么,只需要触发命令的执行方法即可。典型的命令模式包含以下几个角色:
我们以一个简单的家电控制系统为例:支持打开和关闭电灯。通过命令模式,我们可以将“开灯”和“关灯”操作封装成命令对象。
定义命令接口首先定义一个通用的命令接口:
立即学习“go语言免费学习笔记(深入)”;
type Command interface {
Execute()
}
接收者是实际执行动作的对象:
type Light struct {
name string
}
func (l *Light) On() {
fmt.Printf("%s 的灯打开了\n", l.name)
}
func (l *Light) Off() {
fmt.Printf("%s 的灯关闭了\n", l.name)
}
创建开灯和关灯的具体命令:
type LightOnCommand struct {
light *Light
}
func NewLightOnCommand(light *Light) *LightOnCommand {
return &LightOnCommand{light: light}
}
func (c *LightOnCommand) Execute() {
c.light.On()
}
type LightOffCommand struct {
light *Light
}
func NewLightOffCommand(light *Light) *LightOffCommand {
return &LightOffCommand{light: light}
}
func (c *LightOffCommand) Execute() {
c.light.Off()
}
遥控器持有一个命令对象,并在其按钮被按下时执行命令:
type RemoteControl struct {
command Command
}
func (r *RemoteControl) PressButton() {
if r.command != nil {
r.command.Execute()
}
}
在 main 函数中组装各个组件:
func main() {
// 创建接收者
livingRoomLight := &Light{name: "客厅"}
// 创建具体命令
onCommand := NewLightOnCommand(livingRoomLight)
offCommand := NewLightOffCommand(livingRoomLight)
// 创建调用者
remote := &RemoteControl{}
// 模拟按下开灯按钮
remote.command = onCommand
remote.PressButton()
// 模拟按下关灯按钮
remote.command = offCommand
remote.PressButton()
}
输出结果:
客厅 的灯打开了 客厅 的灯关闭了
命令模式的一个优势是容易支持撤销。只需在 Command 接口中增加 Undo 方法:
type Command interface {
Execute()
Undo()
}
然后在具体命令中实现撤销逻辑。例如,开灯命令的撤销就是关灯:
func (c *LightOnCommand) Undo() {
c.light.Off()
}
func (c *LightOffCommand) Undo() {
c.light.On()
}
调用者也可以记录上一次执行的命令,以便撤销:
type RemoteControl struct {
command Command
history []Command
}
func (r *RemoteControl) PressButton() {
if r.command != nil {
r.command.Execute()
r.history = append(r.history, r.command)
}
}
func (r *RemoteControl) Undo() {
if len(r.history) > 0 {
last := r.history[len(r.history)-1]
last.Undo()
r.history = r.history[:len(r.history)-1]
}
}
这种模式特别适合以下情况:
基本上就这些。Golang 虽然没有传统面向对象语言的语法特性,但通过接口和结构体组合,依然能清晰实现命令模式,提升代码的灵活性和可维护性。关键在于理解“将操作封装为对象”这一核心思想。
以上就是如何用Golang应用命令模式_Golang 命令模式实现实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号