设计模式-命令模式

概念

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

演示

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

设计原则验证

  • 命令对象于执行对象分开,解耦
  • 符合开发封闭原则
相关推荐
缘来是庄6 小时前
设计模式之访问者模式
java·设计模式·访问者模式
hqxstudying8 小时前
Java创建型模式---单例模式
java·数据结构·设计模式·代码规范
花好月圆春祺夏安10 小时前
基于odoo17的设计模式详解---装饰模式
数据库·python·设计模式
fie888910 小时前
浅谈几种js设计模式
开发语言·javascript·设计模式
哆啦A梦的口袋呀10 小时前
《深入设计模式》模式结构汇总
设计模式
花好月圆春祺夏安10 小时前
基于odoo17的设计模式详解---单例模式
单例模式·设计模式
在未来等你13 小时前
设计模式精讲 Day 22:模板方法模式(Template Method Pattern)
设计模式·模板方法模式·软件架构·java开发·面向对象设计·设计模式实战·java应用开发
花好月圆春祺夏安14 小时前
基于odoo17的设计模式详解---代理模式
设计模式·代理模式
Small black human1 天前
设计模式-应用分层
设计模式
码农秋1 天前
设计模式系列(10):结构型模式 - 桥接模式(Bridge)
设计模式·桥接模式