This is the sixth day of my participation in the August Text Challenge.More challenges in August

A list,

Observer model

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.

Observer mode has two roles:

  • The target object
  • The observer

The simple flow of observer mode:

  1. Registers the observer to the observer list of the target object
  2. The target object performs the notify operation
  3. The target object calls the observer’s update method, passing the notification to the observer

Contact with reality:

Subscription to newspapers and periodicals. When you subscribe to a newspaper, a new copy of the newspaper will be delivered to you every day. The newspaper company will distribute as many copies as the number of subscribers. The relationship between the newspaper company and its subscribers is the “one-to-many” relationship mentioned at the beginning of the article.

specific general
Leave your number at the newspaper Registers the observer in the target object
The newspaper informed its subscribers of the news Call the corresponding method on the target object via a reference to the observer

Publish and subscribe

In software architecture, publish-subscribe is a messaging paradigm in which a sender of a message (called a publisher) does not directly send the message to a specific recipient (called a subscriber). Instead, they divide published messages into different categories without knowing which subscribers, if any, might exist. Similarly, subscribers can express interest in one or more categories and receive only messages of interest without knowing which publishers (if any) exist.

Between publishers and subscribers exists a third component, called the event hub or event channel, which maintains the link between publishers and subscribers, filtering all incoming messages from publishers and distributing them to subscribers accordingly.

The publish-subscribe model has three roles:

  • Event center
  • The subscriber
  • The publisher

A simple process for the publish-subscribe model:

  1. Subscribers need to subscribe to the event center for the specified events
  2. The publisher needs to publish the specified event to the event center
  3. The event center notifies subscribers

Two, simple implementation

Observer model

class Subject{/ / the target class
    constructor(){
        this.subjectList = [];              // List of observers
    }
    add(observer){                          // Register the observer
        this.subjectList.push(observer)
    }
    notify(context){                        // Issue a notification
        this.subjectList.forEach(observer= > observer.update(context));
    }
    remove(fn){                             // Remove the observer
        this.subjectList.splice(this.subjectList.indexOf(fn),1)}}class Observer{                             / / observer
    update(data){
        console.log('The target object sends a notification:${data}`)
        /** * The corresponding business logic */}}var Subject1 = new Subject()1 / / target
var Subject2 = new Subject()2 / / target

var Observer1 = new Observer()// Observer 1
var Observer2 = new Observer()// Observer 2

Subject1.add(Observer1);/ / register
Subject1.add(Observer2);/ / register
Subject2.add(Observer1);/ / register

Subject1.notify('test1')// Issue a notification
Subject2.notify('test2')// Issue a notification
Copy the code

Publish and subscribe

class PubSub {
  constructor() {
    // Maintain events and subscription behavior
    this.events = {};
  }
  /** * subscribe to events */
  subscribe(topic, callback) {
    if (!this.events[topic]) {
      this.events[topic] = [];
    }
    this.events[topic].push(callback);
  }
  /** * Release event *@param {String} Topic Event type *@param {Any} Data published content */
  publish(topic, data) {
    // Retrieve the corresponding topic callback function
    const callbacks = this.events[topic];
    if (callbacks) {
      callbacks.forEach(cb= >{ cb(data); }); }}}const pubSub = new PubSub();
pubSub.subscribe("open".(data) = > {
  console.log(data);
});
pubSub.publish("open", { open: true });

Copy the code

Three, the difference between the two

Image from this article

This classic diagram illustrates the difference between the observer model and the publish-subscribe model

  1. In the observer pattern, the target is directly related to the observer, whereas in the publish-subscribe pattern, the subscribers and publishers are related by the event center.

    Observer pattern: The target and observer are low coupled and have a strong dependency.

    Publish-subscribe: Subscribers and publishers are completely decoupled due to the presence of the event center.

  2. To subscribe to the target event, observers must add themselves to the target (Subject) for management because there is no event center.

    The target cannot delegate notify to the event center when it fires an event, so it must notify all observers itself.

  3. From a code implementation perspective,

    The Observer pattern is target-oriented and observer programming.

    The publish-subscribe pattern is programmed for the dispatch center.

Three, pay attention

  1. In the given example, the observer object is added to the observer list in the Observer mode; Publish-subscribe adds callback functions to the event center. An individual understanding of the observer pattern may prefer to return notification information to the observer itself, whereas the publish-subscribe pattern may favor the processing of the corresponding published event (via callback functions).

  2. In the publish-subscribe model, subscribers and publishers need not be concrete classes for different implementations (there are two ways to implement them above).

Four, two small questions?

1. Are the Observer and publish-subscribe modes the same?

The observer model and the publish/subscribe model are probably like tomatoes and cherry tomatoes.

Some people think it’s essentially the same model, but as described above, there are some differences.

Here’s a quote from the big guy

There is no publish-subscribe pattern among the 24 basic design patterns. As mentioned above, it is just another name for the observer pattern.

But over time, it seems to have grown stronger and become a different design pattern, independent of the observer pattern.

You can probably think of ———— as a subscription-based publishing model just another name for the observer model, but the concept has changed a lot since then.

2. Is the case observer or publish-subscribe?

/ / theme
class Dep {
  constructor(callback) {
    this.subs = []; // The subscriber of the topic
    this.callback = callback;
  }

  // Add subscribers
  addSub(sub) {
    this.subs.push(sub);
    return this;
  }

  // Topic update notification -- call subscriber update to notify all subscribers
  notify() {
    this.subs.forEach(item= > item.update(this.callback)); }}/ / subscriber
class Sub {
  constructor(val) {
    this.val = val;
  }

  update(callback) {
    this.val = callback(this.val); // Execute the subscription topic function
    console.log('After update :'.this.val); }}/ / publisher
class Pub {
  constructor() {
    this.deps = []; // List of published topics
  }

  // Add a theme
  addDep(dep) {
    this.deps.push(dep);
  }

  // Remove the theme
  removeDep(dep) {
    let index = this.deps.indexOf(dep);
    if(index ! = = -1) {
      this.deps.splice(index, 1);
      return true;
    } else {
      return false; }}// Publish the theme
  publish(dep) {
    this.deps.forEach(item= >item == dep && item.notify()); }}// Create a new theme and add subscribers to the theme
let dep1 = new Dep(item= > item * item);
dep1.addSub(new Sub(1)).addSub(new Sub(2)).addSub(new Sub(3));

// Create a publisher
let pub = new Pub();
// Add a theme
pub.addDep(dep1);

// The publisher publishes to notify all subscribers of the topic of the update
pub.publish(dep1);

// Output the result
// Update result :1
// Update result :4
// Update result :9

Copy the code

Five, reference articles:

The difference between subscription publishing and observer

Similarities and differences between the observer model and the publish-subscribe model

Talk about publish subscribe and observer model from an interview question

The difference between the observer model and the subscription publishing model

JS simple implementation of publish and subscribe mode