DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

4 1

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:

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (1)

Collapse
 
artydev profile image
artydev •

Thank you

ACI image

ACI.dev: Fully Open-source AI Agent Tool-Use Infra (Composio Alternative)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Check out our GitHub!