DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

JavaScript Design Patterns - Behavioral - Mediator

Image description

The Mediator pattern allows us to reduce chaotic dependencies between objects by defining an object that encapsulates how a set of objects interact.

The Mediator pattern suggests that we should cease all direct communication between the instances we want to make independent of each other.

Instead, these instances must collaborate indirectly by calling a special mediator object that redirects the calls to appropriate instances.

In the example below, we are creating a class mediator TrafficTower, to let us know all the positions from the airplane instances.

class TrafficTower {
  constructor() {
    this.airplanes = [];
  }

  getPositions() {
    return this.airplanes.map(airplane => {
      return airplane.position.showPosition();
    });
  }
}

class Airplane {
  constructor(position, trafficTower) {
    this.position = position;
    this.trafficTower = trafficTower;
    this.trafficTower.airplanes.push(this);
  }

  getPositions() {
    return this.trafficTower.getPositions();
  }
}

class Position {
  constructor(x,y) {
    this.x = x;
    this.y = y;
  }

  showPosition() {
    return `My Position is ${this.x} and ${this.y}`;
  }
}

export { TrafficTower, Airplane, Position };
Enter fullscreen mode Exit fullscreen mode

A complete example is here ๐Ÿ‘‰ https://stackblitz.com/edit/vitejs-vite-zvu5ed?file=main.js

Conclusion

We can use this pattern when objects communicate between them but in complex ways.


I hope you found it helpful. Thanks for reading. ๐Ÿ™

Let's get connected! You can find me on:

Top comments (1)

Collapse
 
artydev profile image
artydev

Thank you