设计模式-命令模式

概念

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

演示

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

设计原则验证

  • 命令对象于执行对象分开,解耦
  • 符合开发封闭原则
相关推荐
Supersist14 小时前
【设计模式03】使用模版模式+责任链模式优化实战
后端·设计模式·代码规范
geovindu15 小时前
go: Interpreter Pattern
开发语言·设计模式·golang·解释器模式
workflower16 小时前
从拿订单到看方向
大数据·人工智能·设计模式·机器人·动态规划
sensen_kiss20 小时前
CPT304 SoftwareEngineeringII 软件工程 2 Pt.3 设计模式(上)
设计模式·软件工程
mit6.82420 小时前
20种Agent 设计模式
人工智能·设计模式
workflower20 小时前
企业酝酿数智化内驱力
大数据·人工智能·设计模式·机器人·动态规划
likerhood21 小时前
java设计模式 · 适配器模式 (Adapter Pattern)
java·设计模式·适配器模式
蜡笔小马1 天前
04.C++设计模式-桥接模式
c++·设计模式·桥接模式
geovindu1 天前
go:Condition Variable Pattern
开发语言·后端·设计模式·golang·条件变量模式
geovindu1 天前
Python: Condition Variable Pattern
开发语言·python·设计模式·条件变量模式