It's #FrontendFriday - Mediator (Publish Subscribe)

20.05.2022 -

Hello #FrontendFriday readers. Today we show you the next coding pattern from the Behavioral Design Pattern group: Mediator (Publish Subscribe).

What is the mediator?

In short: A mediator is an event channel that stands between all components and manages the interaction between the components.

 

 

To understand this in detail, we first need to understand the difference between Observer and the publish-subscribe pattern.

Difference between Observer and Publish-Subscribe pattern

Observer: A subject (object) contains the entire logic for event management and the event handlers are stored here. This means that all other objects can only subscribe to this one subject => a one-to-many connection.

Publish/Subscribe: The complete communication logic is carried out within an event channel. This event channel contains all interfaces and stores all event handlers. Each object can publish and subscribe to this event channel => a many-to-many connection.

The Mediator extends the principle of the publish-subscribe pattern. It is used at application level and takes care of the event handling of all components. The advantages of the publish-subscribe pattern remain, but the mediator prevents complex relationships between components. There are no strict dependencies between components.

Mediator Illustration

Example: The database has updated its data and wants to communicate this to the diagram. In this case, the database would not directly call a method from the diagram interface, but would publish an event to the mediator. The diagram listens to this event and wants to draw a new shape. To do this, the diagram publishes a new event to the mediator. The shape listens to this event and executes its logic. In short: everything goes through the mediator.

Code-Example

Here is a code example of how the data update from the example above could look:

class Mediator{
  constructor() {

    // Collection of handlers
    let handlers = {}; 

    // Method to publish the change
    this.publish = function(name, args) {
      handlers[name].map(handler => handler(args));
    };

    // Method for subscription on event
    this.subscribe = function(name, handler) {
      if (typeof handlers[name] === 'undefined') {
        handlers[name] = [];
      }
      handlers[name].push(handler);
    }

    // Method to unsubscribe from event
    this.unsubscribe = function(name, handlers) {
      handlers[name] = handlers[name].filter(storedHandler => storedHandler !== handler);
    };
  }
}

class Shape {
  constructor(name, channel) {
    function init() {
      /** ... some load logic ... **/
      channel.publish('loadedShape', this);
    }
    
    this.name = name;
    init();
  };
}

class Diagram {
  constructor(channel) {
    function init() {
      channel.subscribe('newShape', shape => {
        new Shape(shape, channel);
      });
      channel.subscribe('loadedShape', shapeObj => {
        console.log(shapeObj);
      })
    }
    
    init();
  }
}

class Database {
  constructor(channel) {
    function init() {
      this.getUpdates();
    }
    
    this.getUpdates = function() {
      let addedEntities = ['rect1', 'rect2', 'rect3'];
      addedEntities.map(ent => channel.publish('newShape', ent));
    }
    
    init();
  }
}

(function() {
  let mediator = new Mediator();
  let diagram = new Diagram(mediator);
  let database = new Database(mediator);
})()

As soon as the getUpdates() function is called from the database , the data is published in the "newShape" channel. The diagram listens to this "newShape" channel and initializes a new shape there (simplified). The corresponding logic is then called up in the shape. As soon as this is complete, the "loadedShape" channel is published with the associated data. Diagram listens to "loadedShape" and executes a console.log in our example.

Relevance in JavaScript

As the number of components increases, so does the complexity. The use of a mediator makes sense here, as it simplifies the code and increases readability.


Source: https://soshace.com/programming-patterns-publishersubscriber-mediator/

Back to overview

Write a comment

Your e-mail address will not be published. Required fields are marked with *

*Mandatory fields

*