Front-end design mode command mode

Command mode: When you execute the command, publishers and performers separately (such as owners and staff, the boss said so and so who is going to do, and then the waiter went dry, for which relatively few people, a cry will all know if it is thousands. people, this is inappropriate, this time need to separate the publisher and executors). Was added intermediate command object as a transit point.

 

Such as war film, general transfer command
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();

 

Design Principles verification
Command object to execute the object separately, decoupling
Conforms to the Open Closed Principle

 

Guess you like

Origin www.cnblogs.com/wzndkj/p/11870493.html