命令模式将请求封装为对象,使请求可参数化和撤销。Go通过接口定义Command,含Execute方法;具体命令如LightOnCommand持接收者Light并调用其方法;Invoker如RemoteControl调用命令;支持Undo需扩展接口与实现。

在Go语言中,命令模式(Command Pattern)是一种行为设计模式,它将请求封装为对象,从而使你可以用不同的请求、队列或日志来参数化其他对象。命令模式也支持可撤销的操作。实现命令模式的关键是把“操作”变成一个实体——即命令对象。
首先定义一个统一的命令接口,所有具体命令都实现这个接口:
type Command interface {
Execute()
}
这个接口只有一个方法 Execute(),表示执行某个操作。你也可以根据需要扩展为包含 Undo()、Redo() 等方法,用于支持撤销功能。
命令本身不执行逻辑,而是委托给一个“接收者”(Receiver)。比如我们有两个操作:打开灯和关闭灯。
立即学习“go语言免费学习笔记(深入)”;
type Light struct{}
func (l *Light) TurnOn() {
fmt.Println("The light is on")
}
func (l *Light) TurnOff() {
fmt.Println("The 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()
}
每个命令持有一个接收者实例,并在其 Execute 方法中调用接收者的相应方法。
调用者负责触发命令的执行,它不关心命令的具体内容,只调用 Execute 方法:
type RemoteControl struct {
command Command
}
func (r *RemoteControl) PressButton() {
r.command.Execute()
}
</font>
你可以让遥控器持有多个命令,比如支持多个按钮,甚至命令队列。
下面是一个完整的使用流程:
func main() {
// 接收者
light := &Light{}
// 具体命令
onCommand := &LightOnCommand{light: light}
offCommand := &LightOffCommand{light: light}
// 调用者
remote := &RemoteControl{}
// 执行开灯
remote.command = onCommand
remote.PressButton()
// 执行关灯
remote.command = offCommand
remote.PressButton()
}
输出结果:
The light is on如果要支持撤销,可以在命令接口中添加 Undo 方法:
type Command interface {
Execute()
Undo()
}
然后在 LightOnCommand 中实现 Undo 为关灯:
func (c *LightOnCommand) Undo() {
c.light.TurnOff()
}
调用者可以记录上一次执行的命令,以便调用 Undo。
基本上就这些。Go 没有继承,但通过接口和组合,能很自然地实现命令模式,结构清晰且易于扩展。以上就是Golang如何实现命令模式执行操作的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号