设计模式-命令模式

概念

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

演示

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

设计原则验证

  • 命令对象于执行对象分开,解耦
  • 符合开发封闭原则
相关推荐
啦啦啦啦啦zzzz2 小时前
设计模式:建造者模式
c++·设计模式·建造者模式
梓仁沐白3 小时前
【Agent 设计模式】推理技术
设计模式
Kinghiee3 小时前
从使用场景切入前端常见设计模式
前端·设计模式
啦啦啦啦啦zzzz1 天前
设计模式:单例模式和工厂模式
c++·单例模式·设计模式·工厂模式
小白说大模型1 天前
Python 工程化设计模式:AI 项目中的异步流水线与策略模式实战
人工智能·python·设计模式
choumin1 天前
行为型模式——中介者模式
c++·设计模式·中介者模式·行为型模式
若衹如初見2 天前
一步一步学习使用LiveBindings() LiveBindings图像绑定与自定义绑定方法()
学习·命令模式
geovindu2 天前
Java: Chain of Responsibility Pattern
java·开发语言·后端·设计模式·责任链模式·行为模式
workflower3 天前
装备企业的 AI 路线图
人工智能·深度学习·机器学习·设计模式·机器人
geovindu3 天前
CSharp:Chain of Responsibility Pattern
开发语言·后端·设计模式·c#·.net·责任链模式·行为模式