设计模式-命令模式

概念

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

演示

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

设计原则验证

  • 命令对象于执行对象分开,解耦
  • 符合开发封闭原则
相关推荐
z小天才b13 小时前
Java 设计模式完全指南:从入门到精通
java·开发语言·设计模式
kyriewen1114 小时前
Next.js:让你的React应用从“裸奔”到“穿衣服”
开发语言·前端·javascript·react.js·设计模式·ecmascript
A-Jie-Y15 小时前
JAVA设计模式-工厂方法模式
java·设计模式
A-Jie-Y16 小时前
JAVA设计模式-单例模式
java·设计模式
geovindu16 小时前
go: Iterator Pattern
开发语言·设计模式·golang·迭代器模式
Ting.~18 小时前
软件设计师备考笔记【day2】-UML 图解 | 面向对象 | 设计模式
笔记·设计模式·uml
qcx2318 小时前
深入解析,什么是Agent,Agent的 架构与设计模式
设计模式·架构
geovindu1 天前
go: Chain of Responsibility Pattern
开发语言·设计模式·golang·责任链模式
AndreasEmil2 天前
基于多设计模式的抽奖系统 - 测试报告
java·selenium·设计模式·postman
长安11082 天前
设计模式----工厂模式
设计模式