设计模式-命令模式

概念

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

演示

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

设计原则验证

  • 命令对象于执行对象分开,解耦
  • 符合开发封闭原则
相关推荐
geovindu10 小时前
python: Functional Options Pattern
开发语言·后端·python·设计模式·惯用法模式·函数式选项模式
Kel14 小时前
Pregel 为什么会成为LangGraph编排的心脏
人工智能·设计模式·架构
会周易的程序员17 小时前
microLog 后端开发指南
开发语言·c++·物联网·设计模式·日志·iot·aiot
24计网1王仔寿18 小时前
Linux运维与云计算全栈系统化学习指南(Shell+虚拟化+OpenStack+Docker+公私云实战)
linux·课程设计·数据库开发·微信公众平台·neo4j·命令模式·sequoiadb
geovindu19 小时前
go: Functional Options Pattern
开发语言·后端·设计模式·golang·函数式选项模式’·惯用法模式
Kel1 天前
MCP 传输链路全链路拆解:从字节流到协议栈的四层架构之旅
人工智能·设计模式·架构
atunet2 天前
关于算法设计模式的演化与编程范式变迁的技术7
算法·设计模式
geovindu2 天前
go:Timing Functions Pattern
开发语言·后端·设计模式·golang·计时函数模式·性能分析模式
咖啡八杯3 天前
GoF设计模式——备忘录模式
java·后端·spring·设计模式
槑有老呆3 天前
从 Prompt Engineering 到 Harness Engineering:AI 编程的下一次跃迁
设计模式