您的位置:首页 >Golang命令模式实现与操作详解
发布于2025-10-12 阅读(0)
扫一扫,手机访问
命令模式将请求封装为对象,使请求可参数化和撤销。Go通过接口定义Command,含Execute方法;具体命令如LightOnCommand持接收者Light并调用其方法;Invoker如RemoteControl调用命令;支持Undo需扩展接口与实现。

在Go语言中,命令模式(Command Pattern)是一种行为设计模式,它将请求封装为对象,从而使你可以用不同的请求、队列或日志来参数化其他对象。命令模式也支持可撤销的操作。实现命令模式的关键是把“操作”变成一个实体——即命令对象。
首先定义一个统一的命令接口,所有具体命令都实现这个接口:
type Command interface {
Execute()
}
这个接口只有一个方法 Execute(),表示执行某个操作。你也可以根据需要扩展为包含 Undo()、Redo() 等方法,用于支持撤销功能。
命令本身不执行逻辑,而是委托给一个“接收者”(Receiver)。比如我们有两个操作:打开灯和关闭灯。
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()
}
你可以让遥控器持有多个命令,比如支持多个按钮,甚至命令队列。
下面是一个完整的使用流程:
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 没有继承,但通过接口和组合,能很自然地实现命令模式,结构清晰且易于扩展。上一篇:微博关注分组怎么用?实用技巧分享
下一篇:AI制作海浪logo图标教程
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9