设计模式-命令模式

概念

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

演示

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

设计原则验证

  • 命令对象于执行对象分开,解耦
  • 符合开发封闭原则
相关推荐
黑不溜秋的3 小时前
C++ 设计模式 - 策略模式
c++·设计模式·策略模式
付聪12105 小时前
策略模式介绍和代码示例
设计模式
ThereIsNoCode7 小时前
「软件设计模式」状态模式(State)
设计模式·状态模式
菜鸟一枚在这13 小时前
深入理解设计模式之代理模式
java·设计模式·代理模式
mjr15 小时前
设计模式-Java
java·设计模式
yuanpan15 小时前
23种设计模式之《组合模式(Composite)》在c#中的应用及理解
开发语言·设计模式·c#·组合模式
FLZJ_KL17 小时前
【设计模式】【创建型模式】单例模式(Singleton)
java·单例模式·设计模式
万兴丶19 小时前
Unity 适用于单机游戏的红点系统(前缀树 | 数据结构 | 设计模式 | 算法 | 含源码)
数据结构·unity·设计模式·c#
菜鸟一枚在这19 小时前
深入剖析抽象工厂模式:设计模式中的架构利器
设计模式·架构·抽象工厂模式
码熔burning19 小时前
(三)趣学设计模式 之 抽象工厂模式!
设计模式·抽象工厂模式