The introduction

This article is practical and very simple. So after a brief introduction, I’ll go straight to the code to demonstrate.

Publish and subscribe model: Metaphor: You can also say subscribe and publish is easy to understand. For example, when we shop online, we first put the items we need to buy into the shopping cart. This process is similar to subscription. When the purchase is finished, we pay for it. Implementation: store subscribed events in an array and execute observer mode in sequence when triggered for publication:Copy the code

What’s the difference between publish and subscribe and observer?

Publish and subscribe is a direct relationship between publish and subscribe. Once you subscribe, publish is ready. The observer pattern is also publish and subscribe in nature, but publish and subscribe are related.

Publish and subscribe model

const fs = require("fs");

interface events {
     arr:Array<Function>,
     on(fn:Function) :void,
     emit():void,}let events = {
    arr: [].on(fn) {
    	this.arr.push(fn);
    },
    emit(){
    	this.arr.forEach(fn= > fn())
    }
}

interface IPerson {
	name: string,
    age: number,
}
let person = {} as IPerson;

events.on(() = > {
	if(Object.keys(person).length === 2) {
    	console.log(person)
    }
})
events.on(() = > {
	console.log('Second event subscribed to')
})
fs.readFile("./age.txt".'utf-8'.(err,data) = > {
	person.age = data;
    events.emit();
})
fs.readFile("./name.txt".'utf-8'.(err,data) = > {
	person.name = data;
    events.emit();
})


Copy the code

Observer model

class Baby {// Observed
    name:string  // The instance has a name attribute on it
    state: string
    observers: Observer[]
    constructor(name:string) {
    	this.name = name
        this.observers = []
        this.state = 'Baby cold'
    }
    attach(objArg) {
    	this.observers.push(objArg);
    }
    setState(newState) {
    	this.state = newState;
        this.observers.forEach(o= > o.update(this)); }}class Observer {
    name: string
    constructor(name:string){
    	this.name = name;
    }
    update(baby: Baby) {
    	console.log(baby.name + this.name + baby.state)
    }
}
let baby = new Baby('Ming');
let father = new Observer('Little Ming Baba')
let mother = new Observer('Xiao Ming Ma Ma')
baby.attach(father);
baby.attach(mother);
baby.setState('I'm hot);
baby.setState('I'm not hot or cold.');Copy the code