设计模式-命令模式

概念

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

演示

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

设计原则验证

  • 命令对象于执行对象分开,解耦
  • 符合开发封闭原则
相关推荐
用户84913717547169 小时前
JustAuth实战系列(第5期):建造者模式进阶 - AuthRequestBuilder设计解析
java·设计模式·架构
只因在人海中多看了你一眼9 小时前
B.10.01.5-电商系统的设计模式应用实战
设计模式
希望_睿智13 小时前
实战设计模式之代理模式
c++·设计模式·架构
Freedom风间1 天前
前端必学-完美组件封装原则
前端·javascript·设计模式
王彬泽1 天前
【设计模式】代理模式
设计模式·代理模式
过客随尘1 天前
EventBus设计
设计模式
易元1 天前
模式组合应用-适配器模式
设计模式
程序视点2 天前
设计模式之原型模式!附Java代码示例!
java·后端·设计模式
玄妙尽在颠倒间2 天前
设计模式——模板模式
设计模式
极光雨雨2 天前
【设计模式】模板方法模式
设计模式·模板方法模式