DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

4 1

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

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:

Build seamlessly, securely, and flexibly with MongoDB Atlas. Try free.

Build seamlessly, securely, and flexibly with MongoDB Atlas. Try free.

MongoDB Atlas lets you build and run modern apps in 125+ regions across AWS, Azure, and Google Cloud. Multi-cloud clusters distribute data seamlessly and auto-failover between providers for high availability and flexibility. Start free!

Learn More

Top comments (1)

Collapse
 
artydev profile image
artydev

Thank you

Gen AI apps are built with MongoDB Atlas

Gen AI apps are built with MongoDB Atlas

MongoDB Atlas is the developer-friendly database for building, scaling, and running gen AI & LLM apps—no separate vector DB needed. Enjoy native vector search, 115+ regions, and flexible document modeling. Build AI faster, all in one place.

Start Free

👋 Kindness is contagious

Dive into this thoughtful piece, beloved in the supportive DEV Community. Coders of every background are invited to share and elevate our collective know-how.

A sincere "thank you" can brighten someone's day—leave your appreciation below!

On DEV, sharing knowledge smooths our journey and tightens our community bonds. Enjoyed this? A quick thank you to the author is hugely appreciated.

Okay