设计模式-命令模式

概念

  • 执行命令时,发布者和执行者分开
  • 中间加入命令对象,作为中转站

演示

js 复制代码
class Receiver {
    exec() {
        console.log('执行')
    }
}

class Command {
    constructor(receiver) {
        this.receiver = receiver;
    }
    cmd() {
        console.log('触发命令')
        this.receiver.exec()
    }
}

class Invoker {
    constructor(command) {
        this.command = command
    }
    invoke() {
        console.log('开始')
        this.command.cmd()
    }
}

// 士兵
let soldier = new Receiver()
// 小号手
let trumpeter = new Command(soldier)
// 将军
let general = new Invoker(trumpeter)
general.invoke()

JS中的应用

  • 网页富文本编辑器操作,浏览器封装了一个命令对象
  • document.execCommand('bold')
  • document.execCommand('undo')

设计原则验证

  • 命令对象于执行对象分开,解耦
  • 符合开发封闭原则
相关推荐
槑有老呆1 天前
别再手搓 Prompt 了,那个叫"手动挡循环"
设计模式
用户6919026813392 天前
Vibe Coding 开发项目的基本范式
人工智能·设计模式·代码规范
怕浪猫3 天前
领域特定语言(Domain-Specific Language, DSL)
设计模式·程序员·架构
Larcher5 天前
AI Loop:让AI像人一样自主完成任务的核心机制
javascript·人工智能·设计模式
咖啡八杯6 天前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
:mnong6 天前
学习创建结构行为设计模式
设计模式
w_t_y_y6 天前
Agent设计模式(四)多模态融合模式(Multi-Modal Fusion)
设计模式
zhouhui0016 天前
订单状态的 if-else 地狱上线就崩——状态模式的工业级落地
设计模式
geovindu6 天前
go: Reactor Pattern
开发语言·后端·设计模式·golang·反应器模式