Contact Me

Mediator

 This pattern allows you to define a separate object (the mediator) that controls the communication between a set of objects (the colleagues). This can be useful when you want to reduce the dependency between objects, and when you want to centralize the control of communication between objects in a single place.


Here is an example of the mediator pattern in JavaScript:


class Mediator {

constructor() {

  this.colleagues = [];

}

register(colleague) {

  this.colleagues.push(colleague);

  colleague.setMediator(this);

}

send(message, sender) {

  this.colleagues.forEach(colleague => {

   if (colleague !== sender) {

    colleague.receive(message);

   }

  });

}

}

class Colleague {

constructor(name) {

  this.name = name;

  this.mediator = null;

}

setMediator(mediator) {

  this.mediator = mediator;

}

send(message) {

  console.log(`$ {this.name } sends message: '$ {message }'.`);

  this.mediator.send(message, this);

}

receive(message) {

  console.log(`$ {this.name } receives message: '$ {message}'.`);

}

}

const mediator = new Mediator();

const colleague1 = new Colleague('Colleague 1');

const colleague2 = new Colleague('Colleague 2');

const colleague3 = new Colleague('Colleague 3');

mediator.register(colleague1);

mediator.register(colleague2);

mediator.register(colleague3);

colleague1.send('Hello, World!');

// Output:

// Colleague 1 sends message: 'Hello, World!'.

// Colleague 2 receives message: 'Hello, World!'.

// Colleague 3 receives message: 'Hello, World!'.

colleague2.send('Hi, there!');

// Output:

// Colleague 2 sends message: 'Hi, there!'.

// Colleague 1 receives message: 'Hi, there!'.

// Colleague 3 receives message: 'Hi, there!'.

colleague3.send('How are you?');

// Output:

// Colleague 3 sends message: 'How are you?'.

// Colleague 1 receives message: 'How are you?'.

// Colleague 2 receives message: 'How are you?'.


In this example, the Mediator class is a class that controls the communication between a set of Colleague objects, and the Colleague class is a class that represents an object that communicates with other objects through the mediator. The Mediator class has a register() method for registering colleagues and a send() method for sending messages to registered colleagues.

The Colleague class has a setMediator() method for setting the mediator and a send() method for sending messages through the mediator.

To use the mediator pattern, we create an instance of the Mediator class, and then create instances of the Colleague class. We register the colleague objects with the mediator using the register() method, and then set the mediator for the colleague objects using the send() method of the Colleague class to send messages through the mediator.