设计模式-命令模式

概念

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

演示

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

设计原则验证

  • 命令对象于执行对象分开,解耦
  • 符合开发封闭原则
相关推荐
努力也学不会java2 小时前
【设计模式】状态模式
java·设计模式·状态模式
.豆鲨包2 小时前
【设计模式】单例模式
java·单例模式·设计模式
lpfasd1233 小时前
第2课:Agent系统架构与设计模式
设计模式·系统架构
青草地溪水旁6 小时前
设计模式(C++)详解—原型模式(1)
c++·设计模式·原型模式
青草地溪水旁7 小时前
设计模式(C++)详解—原型模式(2)
c++·设计模式·原型模式
青草地溪水旁7 小时前
设计模式(C++)详解—原型模式(3)
c++·设计模式·原型模式
new_daimond9 小时前
设计模式-装饰器模式详解
设计模式·装饰器模式
SamDeepThinking21 小时前
用设计模式重构核心业务代码的一次实战
java·后端·设计模式
青草地溪水旁1 天前
设计模式(C++)详解——建造者模式(2)
c++·设计模式·建造者模式