前端设计模式 命令模式

命令模式:执行命令时,发布者和执行者分开(比如老板和服务员,老板说谁谁谁去干什么,然后服务员就去干了,这适合人比较少,一吆喝就都知道了。如果是上千人,这样就不合适了,这个时候需要发布者和执行者分开)。中间加入命令对象,作为中转站。
比如战争片中,将军传递命令
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();
设计原则验证
命令对象于执行对象分开,解耦
符合开放封闭原则
原文地址:https://www.cnblogs.com/wzndkj/p/11870493.html