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:

Image of Docusign

๐Ÿ› ๏ธ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (1)

Collapse
 
artydev profile image
artydev โ€ข

Thank you

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

๐Ÿ‘‹ Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Communityโ€”every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple โ€œthank youโ€ goes a long wayโ€”express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay