设计模式-命令模式

概念

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

演示

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')

设计原则验证

  • 命令对象于执行对象分开,解耦
  • 符合开发封闭原则
相关推荐
志摩凛7 小时前
被产品经理逼疯后,我们重构了移动端上传组件——2026最新成果复盘
设计模式·架构
ximu_polaris10 小时前
设计模式(c++)-结构型模式-装饰器模式
c++·设计模式·装饰器模式
两年半的个人练习生^_^10 小时前
每日一学:设计模式之适配器模式
java·设计模式·适配器模式
我爱cope11 小时前
【从0开始学设计模式-12| 代理模式】
设计模式·代理模式
geovindu12 小时前
go: Composite Pattern
设计模式·golang·组合模式
敖正炀13 小时前
行为型模式-状态模式
设计模式
我的征途是星辰大海。13 小时前
设计模式(学习笔记)(第一章)
笔记·学习·设计模式
敖正炀13 小时前
创建型模式-抽象工厂模式
设计模式
敖正炀13 小时前
创建型模式-工厂方法模式
设计模式
敖正炀13 小时前
创造型模式-单例模式
设计模式