设计模式-命令模式

概念

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

演示

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

设计原则验证

  • 命令对象于执行对象分开,解耦
  • 符合开发封闭原则
相关推荐
geovindu5 小时前
go: Chain of Responsibility Pattern
开发语言·设计模式·golang·责任链模式
AndreasEmil18 小时前
基于多设计模式的抽奖系统 - 测试报告
java·selenium·设计模式·postman
长安110818 小时前
设计模式----工厂模式
设计模式
星轨zb18 小时前
什么是Spring设计模式:单例、工厂与代理
java·spring·设计模式
悟051518 小时前
设计模式-状态模式
设计模式·状态模式
geovindu1 天前
go: Proxy Pattern
开发语言·后端·设计模式·golang·代理模式
A-Jie-Y1 天前
JAVA23种设计模式
java·设计模式
小程故事多_802 天前
Claude Code 全流程梳理,从需求输入到工具执行的完整逻辑
人工智能·设计模式·智能体·claude code·harness
cui17875682 天前
排队免单模式:从爆火到优化,探寻实体商业新出路
大数据·人工智能·设计模式·个人开发·设计规范
医疗信息化王工2 天前
26种不良事件表单的通用设计模式与实现
设计模式