设计模式-命令模式

概念

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

演示

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

设计原则验证

  • 命令对象于执行对象分开,解耦
  • 符合开发封闭原则
相关推荐
老蒋每日coding4 小时前
AI Agent 设计模式系列(十八)—— 安全模式
人工智能·安全·设计模式
老蒋每日coding6 小时前
AI Agent 设计模式系列(十六)—— 资源感知优化设计模式
人工智能·设计模式·langchain
老蒋每日coding6 小时前
AI Agent 设计模式系列(十七)—— 推理设计模式
人工智能·设计模式
冷崖6 小时前
桥模式-结构型
c++·设计模式
连山齐名6 小时前
设计模式之一——堵塞队列
设计模式
会员果汁6 小时前
19.设计模式-命令模式
设计模式·命令模式
茶本无香6 小时前
设计模式之六—组合模式:构建树形结构的艺术
java·设计模式·组合模式
橘色的喵7 小时前
嵌入式 C++ 高性能流式架构的设计
数码相机·设计模式
会员果汁7 小时前
20.设计模式-职责链模式
设计模式
羊群智妍16 小时前
2026GEO监测工具精选:免费AI搜索优化监测工具实用指南
百度·微信·命令模式·新浪微博·segmentfault