设计模式-命令模式

概念

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

演示

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

设计原则验证

  • 命令对象于执行对象分开,解耦
  • 符合开发封闭原则
相关推荐
咖啡八杯1 小时前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
:mnong5 小时前
学习创建结构行为设计模式
设计模式
w_t_y_y7 小时前
Agent设计模式(四)多模态融合模式(Multi-Modal Fusion)
设计模式
zhouhui0019 小时前
订单状态的 if-else 地狱上线就崩——状态模式的工业级落地
设计模式
geovindu9 小时前
go: Reactor Pattern
开发语言·后端·设计模式·golang·反应器模式
一只旭宝19 小时前
【C++入门精讲22】常见设计模式
c++·设计模式
许彰午1 天前
38_Java设计模式之装饰器模式
java·设计模式·装饰器模式
geovindu1 天前
python: Reactor Pattern
开发语言·python·设计模式·反应器模式
workflower1 天前
基于机器学习的设备故障预测分析方法
人工智能·算法·机器学习·设计模式·语言模型·自然语言处理·重构
迷茫运维路1 天前
Golang架构目录设计与设计模式教程
设计模式·golang