登录
首页 >  Golang >  Go教程

Golang命令模式实现与执行示例

时间:2025-09-24 13:38:28 217浏览 收藏

偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《Golang命令模式封装与执行实例》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!

命令模式通过将请求封装为对象,实现调用者与接收者的解耦。示例中定义了Command接口及LightOnCommand、LightOffCommand具体实现,RemoteControl作为调用者通过Execute方法间接控制Light状态,输出“Light is on”和“Light is off”,支持扩展撤销、队列等功能。

Golang命令模式请求封装与执行示例

在Go语言中,命令模式是一种行为设计模式,它将请求封装为对象,从而使你可以用不同的请求、队列或日志来参数化其他对象。命令模式也支持可撤销的操作。下面通过一个简单的示例展示如何在Golang中实现命令模式的请求封装与执行。

定义命令接口

首先定义一个统一的命令接口,所有具体命令都实现该接口的 Execute 方法。

type Command interface {
    Execute()
}

实现具体命令

假设我们有一个电灯(Light)设备,可以通过打开和关闭命令来控制。先定义设备:

type Light struct {
    state string
}

func (l *Light) TurnOn() {
    l.state = "on"
    fmt.Println("Light is on")
}

func (l *Light) TurnOff() {
    l.state = "off"
    fmt.Println("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()
}

使用命令调用者(Invoker)

调用者不直接操作设备,而是持有命令对象并执行它。

type RemoteControl struct {
    command Command
}

func (r *RemoteControl) PressButton() {
    if r.command != nil {
        r.command.Execute()
    }
}

完整示例演示

将所有部分组合起来,演示命令的封装与执行:

package main

import "fmt"

// Command 接口
type Command interface {
    Execute()
}

// 接收者:灯
type Light struct {
    state string
}

func (l *Light) TurnOn() {
    l.state = "on"
    fmt.Println("Light is on")
}

func (l *Light) TurnOff() {
    l.state = "off"
    fmt.Println("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()
}

// 调用者
type RemoteControl struct {
    command Command
}

func (r *RemoteControl) PressButton() {
    if r.command != nil {
        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()
}

输出结果:

Light is on
Light is off

通过这种方式,调用者(RemoteControl)与接收者(Light)完全解耦。你可以轻松替换命令,实现宏命令(组合多个命令)、撤销操作(添加 Undo 方法)或命令队列等功能。

基本上就这些,命令模式在任务调度、操作记录、UI按钮等场景中非常实用。结构清晰,扩展性强。

到这里,我们也就讲完了《Golang命令模式实现与执行示例》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>