设计模式-命令模式

概念

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

演示

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

设计原则验证

  • 命令对象于执行对象分开,解耦
  • 符合开发封闭原则
相关推荐
J_liaty3 小时前
23种设计模式一迭代器模式
设计模式·迭代器模式
驴儿响叮当20107 小时前
设计模式之策略模式
设计模式·策略模式
驴儿响叮当20109 小时前
设计模式之中介模式
设计模式
驴儿响叮当201012 小时前
设计模式之命令模式
设计模式·命令模式
驴儿响叮当201014 小时前
设计模式之适配器模式
设计模式·适配器模式
HEU_firejef15 小时前
设计模式——代理模式
设计模式·代理模式
Coder_Boy_16 小时前
从单体并发工具类到分布式并发:思想演进与最佳实践(二)
java·spring boot·分布式·微服务·设计模式
TvxzFtDBIxok16 小时前
基于人工势场法的船舶自动避碰系统MATLAB实现之旅
命令模式
geovindu1 天前
python: Memento Pattern
开发语言·python·设计模式·备忘录模式
HEU_firejef1 天前
设计模式——单例模式
单例模式·设计模式