设计模式-命令模式

概念

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

演示

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

设计原则验证

  • 命令对象于执行对象分开,解耦
  • 符合开发封闭原则
相关推荐
妙蛙种子31111 小时前
【Java设计模式 | 创建者模式】 原型模式
java·开发语言·后端·设计模式·原型模式
zhaoshuzhaoshu13 小时前
设计模式之行为型设计模式详解
python·设计模式
楼田莉子13 小时前
设计模式:构造器模式
开发语言·c++·后端·学习·设计模式
小程故事多_8015 小时前
从Claude Code源码泄露,读懂12个可复用的Agentic Harness设计模式(生产级落地指南)
人工智能·设计模式·aigc·ai编程·harness
We་ct2 天前
JS手撕:函数进阶 & 设计模式解析
开发语言·前端·javascript·设计模式·面试·前端框架
冷小鱼2 天前
设计模式全景指南:23种模式深度解析与Python实现
设计模式
楼田莉子2 天前
设计模式:创建型设计模式简介
服务器·开发语言·c++·设计模式
UrSpecial2 天前
设计模式:观察者模式
观察者模式·设计模式