设计模式-命令模式

概念

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

演示

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

设计原则验证

  • 命令对象于执行对象分开,解耦
  • 符合开发封闭原则
相关推荐
2401_868534787 小时前
网规备考_2.4 路由协议
c++·设计模式
cpp_learner9 小时前
C++ 实现责任链模式(Chain of Responsibility):从一堆 if-else 到可插拔的处理管道
c++·设计模式
码匠许师傅9 小时前
【设计模式精讲】23.备忘录模式(Memento)
c++·设计模式·软件工程·uml·备忘录模式
新知图书1 天前
第8章 多智能体协同
人工智能·设计模式·智能体
京师20万禁军教头1 天前
39面向对象(高级)-设计模式
java·开发语言·设计模式
新知图书1 天前
3.5 智能体设计模式1:反应式智能体与自动导航案例
人工智能·设计模式·智能体
码匠许师傅1 天前
【设计模式精讲】21.迭代器模式(Iterator)
c++·设计模式·rpc·迭代器模式·软件工程·uml
geovindu2 天前
CSharp: Command Pattern
开发语言·后端·c#·.net·.netcore·命令模式·行为模式
Carl_奕然2 天前
【智能体】Agent的四种设计模式之:React(2026最新版)
javascript·人工智能·python·react.js·设计模式·语言模型
cfm_29142 天前
Spring核心设计模式
java·spring·设计模式