设计模式-命令模式

概念

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

演示

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

设计原则验证

  • 命令对象于执行对象分开,解耦
  • 符合开发封闭原则
相关推荐
geovindu6 小时前
go: Proxy Pattern
开发语言·后端·设计模式·golang·代理模式
A-Jie-Y8 小时前
JAVA23种设计模式
java·设计模式
小程故事多_8011 小时前
Claude Code 全流程梳理,从需求输入到工具执行的完整逻辑
人工智能·设计模式·智能体·claude code·harness
cui178756815 小时前
排队免单模式:从爆火到优化,探寻实体商业新出路
大数据·人工智能·设计模式·个人开发·设计规范
医疗信息化王工15 小时前
26种不良事件表单的通用设计模式与实现
设计模式
mounter62515 小时前
【内核精进】Linux Kernel 设计模式(一):引用计数与可见性的艺术
linux·设计模式·linux kernel
workflower15 小时前
机器人应用-高空立面清洁
人工智能·深度学习·设计模式·机器人·软件工程·软件构建
likerhood16 小时前
设计模式:原型模式(Prototype Pattern)java版本
java·设计模式·原型模式
小程故事多_801 天前
从Claude Code源码中,拆解13个可直接复用的Agentic Harness设计模式(生产级实战解析)
人工智能·设计模式·智能体·claude code·harness
踩着两条虫1 天前
VTJ 平台六大设计模式落地实战指南
开发语言·前端·人工智能·低代码·设计模式·重构·架构