设计模式-命令模式

概念

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

演示

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

设计原则验证

  • 命令对象于执行对象分开,解耦
  • 符合开发封闭原则
相关推荐
Coder_Boy_14 小时前
Java高级_资深_架构岗 核心知识点全解析(模块四:分布式)
java·spring boot·分布式·微服务·设计模式·架构
资深web全栈开发1 天前
设计模式之解释器模式 (Interpreter Pattern)
设计模式·解释器模式
漠月瑾-西安1 天前
React-Redux Connect 高阶组件:从“桥梁”到“智能管家”的深度解析
react.js·设计模式·react-redux·高阶组件·connect高阶租单间·原理理解
J_liaty1 天前
23种设计模式一备忘录模式
设计模式·备忘录模式
驴儿响叮当20102 天前
设计模式之建造者模式
设计模式·建造者模式
知识即是力量ol2 天前
口语八股—— Spring 面试实战指南(终篇):常用注解篇、Spring中的设计模式
java·spring·设计模式·面试·八股·常用注解
茶本无香2 天前
【无标题】
java·设计模式·策略模式
郝学胜-神的一滴2 天前
当AI遇见架构:Vibe Coding时代的设计模式复兴
开发语言·数据结构·人工智能·算法·设计模式·架构
『往事』&白驹过隙;2 天前
浅谈PC开发中的设计模式搬迁到ARM开发
linux·c语言·arm开发·设计模式·iot