Continue to learn hard PS: learn from — nuggets of JavaScript design pattern core principle and application booklet

A concept,

The observer pattern defines a one-to-many dependency that allows multiple observer objects to listen to a target object at the same time. When the state of the target object changes, all observer objects are notified so that they can update automatically.

Second, the case

Code + Case description

  • 1. Case description

Robot operations Add/remove combat robots through the master control system. Robots perform operations such as attack and retreat according to the instructions issued by the master system

// Class RobotControl {constructor() {this. Robots = []; // Add (robot) {this.robots. Push (robot); ForEach ((item, index) => {if(robot === item) {this.robots. Splice (index, index) {this.robots. ForEach ((item)=>{item.attack()})} // Notify the robot to retreat notifyDefence() { ForEach ((item)=>{item.defence()})}} // Robot class {constructor(name) {this.name = name; } attack() {console.log(' robot ${this.name} launches missile attack '); } defence(name) {console.log(' robot ${this.name} withdraws from the battlefield to defend '); } } const r1 = new Robot('r1'); const r2 = new Robot('r2'); const r3 = new Robot('r3'); const rc = new RobotControl(); rc.add(r1); rc.add(r2); rc.add(r3); rc.notifyAttack(); rc.delete(r2) rc.notifyDefence(); // Result: // Robot R1 launches a missile attack // Robot R2 launches a missile attack // Robot R3 launches a missile attack // Robot R1 withdraws from the battlefield to defend // Robot R3 withdraws from the battlefield to defendCopy the code

PS: The follow-up will be improved after the summary of Vue2 version