This article will introduce you to the publish-subscribe and observer patterns, and talk about the differences between the two. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Some time ago, I had a whim and wrote promises one by one. Promise happens to be the subscription publishing model. The mobx used for development at work is also an observer model. Although they are all used, but I have never thought about the difference between the two, and the difference analysis on the Internet is confusing. I will combine a summary of my own and the simplest implementation (it is also easy to understand because it is simple) to share and deepen my understanding of the two
1. Implementation ideas
2. Code implementation
interface eventHub { arr: Array<Function>; on(fn: Function): void; emit(): void; } interface Person { age: number; name: string; } let eventHub: eventHub = { arr: [] as Array<Function>, // 订阅 on(fn: Function) { this.arr.push(fn); }, // 发布 emit() { this.arr.forEach((fn) => fn()); }, }; let person: Person = {} as Person; eventHub.on(() => { //订阅的事件里判断当 person长度为2时 打印person, if (Object.keys(person).length == 2) { console.log(person); } }); setTimeout(function () { person.age = 27; //发布的时候去遍历 this.arr 并执行第一次 eventHub.emit(); }, 10); setTimeout(function () { person.name = "Zoe"; //发布的时候去遍历 this.arr 并执行第二次 eventHub.emit(); }, 20);
3.Result
Although it was published twice, in the end the console in on was only executed once due to external conditions
1. Implementation idea
is similar to the observer pattern, but needs to be divided into an observer and the observed
2. Code implementation
// 被观察者 class Subject { name: string; //实例上定义一个name属性 state: string; observers: any[]; constructor(name:string) { this.name = name; this.observers = []; this.state = ""; } attach(o) { //传入观察者 this.observers.push(o); } setState(newState) { this.state = newState; this.observers.forEach((o) => o.update(this)); } } // 观察者 class Observer { name: string; constructor(name) { this.name = name; } update(interviewee) { console.log(`${interviewee.name} say to: ${this.name} ZOE的${interviewee.state}`); } } let hr = new Subject("HR"); let observer1 = new Observer("内推者"); let observer2 = new Observer("面试者"); hr.attach(observer1); hr.attach(observer2); hr.setState("面试通过了"); // baby.setState("面试没通过");
3. Implementation result
Programming Video! !
The above is the detailed content of Let's briefly talk about publish, subscribe and observer patterns, and talk about the differences between them.. For more information, please follow other related articles on the PHP Chinese website!