Home >Web Front-end >JS Tutorial >Let's briefly talk about publish, subscribe and observer patterns, and talk about the differences between them.

Let's briefly talk about publish, subscribe and observer patterns, and talk about the differences between them.

青灯夜游
青灯夜游forward
2021-06-18 10:32:111931browse

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.

Let's briefly talk about publish, subscribe and observer patterns, and talk about the differences between them.

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

subscribe to publish

1. Implementation ideas

  • arr Make a cache center for subscribed events
  • Push the things that need to be done through on the arr cache array Middle
  • When waiting for the event to trigger, emit the execution event in sequence

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

Lets briefly talk about publish, subscribe and observer patterns, and talk about the differences between them.

Observer mode

1. Implementation idea

is similar to the observer pattern, but needs to be divided into an observer and the observed

  • The observer and the observed Observers are associated, (internally based on the publish-subscribe model)

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

Lets briefly talk about publish, subscribe and observer patterns, and talk about the differences between them.

The difference between the two

eventHub publish and subscribe

  • on(subscribe ) and publishing (emit). There is no direct connection between them. They rely on the intermediate arr to connect and subscribe one push to arr. When emitting, arr is executed in sequence

##Observer mode

    There is a relationship between the observer and the observed, (internally based on the publish-subscribe model)
  • Pass the instance of the observer as a parameter into the attach method of the observed and cache it in In the observers array
  • When the observer setState is called, the update method of the observer in the cache array observers is called sequentially
For more programming-related knowledge, please visit:

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!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete