设计模式-命令模式

概念

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

演示

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 小时前
结构型设计模式1
设计模式
lapiii3581 小时前
[智能体设计模式] 第五章 :函数调用
microsoft·设计模式
lapiii3581 小时前
[智能体设计模式] 第 1 章:提示链(Prompt Chaining)
设计模式·prompt
昨天的猫3 小时前
《拒绝重复代码!模板模式教你优雅复用算法骨架》
后端·设计模式
L.EscaRC3 小时前
ArkTS分布式设计模式浅析
分布式·设计模式·arkts
Arva .4 小时前
责任链设计模式->规则树
设计模式
WKP94184 小时前
命令设计模式
设计模式
lapiii3588 小时前
[智能体设计模式] 第4章:反思(Reflection)
人工智能·python·设计模式
颜酱19 小时前
理解编程范式(前端角度)
设计模式
将编程培养成爱好21 小时前
C++ 设计模式《账本事故:当备份被删光那天》
开发语言·c++·设计模式·备忘录模式