设计模式-命令模式

概念

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

演示

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

设计原则验证

  • 命令对象于执行对象分开,解耦
  • 符合开发封闭原则
相关推荐
蜡笔小马17 分钟前
06.C++设计模式-装饰模式
c++·设计模式·装饰器模式
悟051540 分钟前
设计模式-策略模式
设计模式·策略模式
UXbot11 小时前
一人独立交付 UI + 前端:AI 驱动 UI 设计工具的五大功能模块深度评测
前端·低代码·ui·设计模式·交互
蜡笔小马15 小时前
07.C++设计模式-组合模式
c++·设计模式·组合模式
雪度娃娃20 小时前
结构型设计模式——享元模式
c++·设计模式·享元模式
今儿敲了吗1 天前
面向对象(三)——设计模式
笔记·设计模式
蜡笔小马1 天前
08.C++设计模式-享元模式
c++·设计模式·享元模式
qq_381338501 天前
Vue3 组合式函数设计模式:从基础封装到高级复用实战
前端·vue.js·设计模式
geovindu2 天前
go: Lock/Mutex Pattern
开发语言·后端·设计模式·golang·互斥锁模式
学习中.........2 天前
常见设计模式
java·设计模式