JavaScript Design Patterns - Behavioral - Mediator

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();
    });
  }
}

lass 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 };

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: