您的位置:首页 >Golang命令模式封装请求对象详解
发布于2025-11-06 阅读(0)
扫一扫,手机访问
命令模式通过封装请求为对象实现调用者与接收者解耦,支持撤销、队列和扩展,适用于Go语言中的遥控操作、任务队列等场景。

在Go语言开发中,命令模式是一种行为设计模式,它将请求封装为对象,从而使你可以用不同的请求、队列或日志来参数化其他对象。命令模式的核心思想是将“执行某个操作”的请求抽象成一个独立的命令对象,这样发送请求的对象(调用者)与接收请求的对象(执行者)之间就实现了松耦合。
命令模式通常包含以下几个角色:
以下是一个简单的命令模式实现,模拟一个遥控器控制灯的开关操作。
// 接收者:灯type Light struct{}
func (l *Light) On() {
println("灯已打开")
}
func (l *Light) Off() {
println("灯已关闭")
}
// 命令接口type Command interface {
Execute()
}
// 具体命令:开灯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) SetCommand(command Command) {
r.command = command
}
func (r *RemoteControl) PressButton() {
if r.command != nil {
r.command.Execute()
}
}
// 客户端使用func main() {
light := &Light{}
onCmd := NewLightOnCommand(light)
offCmd := NewLightOffCommand(light)
remote := &RemoteControl{}
remote.SetCommand(onCmd)
remote.PressButton() // 输出:灯已打开
remote.SetCommand(offCmd)
remote.PressButton() // 输出:灯已关闭
}
使用命令模式能带来以下几个好处:
命令模式适用于以下场景:
基本上就这些。命令模式通过将请求封装成对象,提升了系统的灵活性和可扩展性,在Go语言中借助接口和结构体可以简洁地实现这一模式。
上一篇:喜马拉雅电脑端怎么开弹幕?
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9