Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • System Design Tutorial
  • What is System Design
  • System Design Life Cycle
  • High Level Design HLD
  • Low Level Design LLD
  • Design Patterns
  • UML Diagrams
  • System Design Interview Guide
  • Scalability
  • Databases
Open In App
Next Article:
Factory Method in JavaScript | Design Pattern
Next article icon

Mediator Design Pattern in JavaScript | Design Pattern

Last Updated : 31 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

The Mediator pattern is a behavioral design pattern that promotes loose coupling between objects by centralizing communication between them. It's particularly useful when you have a complex system with multiple objects that need to interact and you want to avoid the tight coupling that can arise from direct object-to-object communication.

Important Topics for the Mediator Design Pattern in JavaScript Design Pattern

  • Understanding the Mediator Pattern in JavaScript Design Pattern
  • Advantages of the Mediator method in JavaScript Design Pattern
  • Disadvantages of the Mediator Method in JavaScript Design Pattern
  • Conclusion

Understanding the Mediator Pattern in JavaScript Design Pattern

The mediator pattern consists of the following key components:

  • Mediator: The Mediator is an interface or class responsible for defining the communication interface between the objects within the system. It acts as a central hub for communication and typically contains methods that allow objects to send and receive messages.
  • Concrete Mediator: This is a specific implementation of the Mediator interface. It manages the interactions between the various objects in the system. It knows how to route messages and coordinate actions between objects.
  • Colleague: Colleagues are individual objects in the system that need to communicate with each other. They are aware of the mediator but don't have direct references to other colleagues. Instead, they send messages to and receive messages from the mediator.

Example:

Let's illustrate the Mediator pattern with an example related to an air traffic control system. In this system, planes (Colleagues) need to communicate with each other to avoid collisions. The Air Traffic Control (Mediator) acts as the central hub for coordinating plane movements.

JavaScript
// Mediator: AirTrafficControl class AirTrafficControl {     requestTakeoff(plane) {         console.log(`Air Traffic Control grants takeoff clearance for ${plane.getName()}.`);     }      requestLanding(plane) {         console.log(`Air Traffic Control clears ${plane.getName()} for landing.`);     } }  // Colleague: Plane class Plane {     constructor(name) {         this.name = name;     }      getName() {         return this.name;     }      requestTakeoff() {         console.log(`${this.name} requests takeoff clearance.`);         airTrafficControl.requestTakeoff(this);     }      requestLanding() {         console.log(`${this.name} requests landing clearance.`);         airTrafficControl.requestLanding(this);     } }  const airTrafficControl = new AirTrafficControl();  const plane1 = new Plane('Flight 123'); const plane2 = new Plane('Flight 456');  plane1.requestTakeoff(); plane2.requestLanding(); 


Untitled
Diagrammatical Representation of Air Traffic Control

Output:

Flight 123 requests takeoff clearance.Air Traffic Control grants takeoff clearance for Flight 123.Flight 456 requests landing clearance.Air Traffic Control clears Flight 456 for landing.

Let's break down Air traffic control to get a better understanding:

1. Mediator

The "AirTrafficControl" class represents the Mediator in this example. It has two methods:

  • "requestTakeoff(plane)": responsible for granting takeoff clearance for a specific plane and logs a message indicating the clearance.
  • "requestLanding(plane)": responsible for clearing a plane for landing and logs a message indicating the clearance.

2. Colleague:

The "Plane" class represents a Colleague or an individual object in this example. It has a constructor that takes the "name" of the plane as a parameter and stores it as an instance variable.

  • "requestTakeoff()" is a method that simulates a plane requesting takeoff clearance.
  • "requestLanding()" is a method that simulates a plane requesting landing clearance.

3. Initialization:

An instance of "AirTrafficControl" is created and assigned to the variable "airTrafficControl". This is our Mediator object. Two instances of "Plane" are created:

  • "plane1" with name 'Flight 123' .
  • "plane2" with the name 'Flight 456'.

4. Interaction:

"Plane1" initiates the interaction by calling "requestTakeoff()".

  • This method logs that 'Flight 123' is requesting takeoff clearance and then invokes "airTrafficControl".
  • "requestTakeoff(this)", where "this" refers to the "plane1" object.
  • "airTrafficControl" receives the request, logs that it grants takeoff clearance for 'Flight 123', and acknowledges the request. Next, "plane2" initiates the interaction by calling "requestLanding()".
  • This method logs that 'Flight 456' is requesting landing clearance and then invokes "airTrafficControl".
  • "requestLanding(this)", where "this" refers to the "plane2" object. Again, "airTrafficControl" receives the request, logs that it clears 'Flight 456' for landing, and acknowledges the request.

This example demonstrates how the Mediator pattern facilitates communication between objects (planes) in a centralized and loosely coupled manner. The "AirTrafficControl" acts as a central hub, coordinating and managing the interactions between the planes, enabling them to request and receive clearances for takeoff and landing.

Advantages of the Mediator method in JavaScript Design Pattern

  • Decoupling: The Mediator pattern reduces direct dependencies between objects, promoting a more loosely coupled system. Colleagues only need to know about the Mediator, not each other, which makes the system more maintainable and extensible.
  • Centralized Control: Centralizing communication in a Mediator can simplify complex interactions in a system. This central hub can enforce rules, coordinate actions, and ensure that communication remains organized.
  • Reusability: Mediators can be reused across different scenarios or projects. Once you have a well-defined Mediator interface or class, you can apply it to various situations where you need to manage interactions between objects.
  • Promotes Single Responsibility Principle: The Mediator pattern encourages the Single Responsibility Principle by isolating communication-related logic in one place, making the codebase cleaner and more modular.

Disadvantages of the Mediator Method in JavaScript Design Pattern

  • Complexity: In some cases, introducing a Mediator can add complexity to the system, especially if you have a small number of objects or if the interactions between objects are straightforward.
  • Performance Overhead: Managing communication through a Mediator can introduce some performance overhead, as all messages pass through this central point. However, this overhead is usually negligible in most applications.
  • Maintaining the Mediator: If the system becomes overly complex or if there are frequent changes in communication requirements, maintaining the Mediator can become challenging.
  • Potential for God Object: Care should be taken not to turn the Mediator into a "God Object" that knows too much about the system. It should focus on facilitating communication, not on handling all logic.

Conclusion

The Mediator design pattern is a valuable tool for managing complex interactions between objects in a system while maintaining loose coupling and modularity. It encourages a more organized and maintainable codebase by centralizing communication. When used appropriately, the Mediator pattern enhances code reusability and promotes the Single Responsibility Principle. However, it's essential to strike a balance and avoid overcomplicating the system with unnecessary mediators. By understanding and applying the Mediator pattern effectively, you can design more flexible and scalable software systems.


Next Article
Factory Method in JavaScript | Design Pattern

R

rudra1807raj
Improve
Article Tags :
  • Design Pattern
  • Geeks Premier League
  • System Design
  • Geeks Premier League 2023

Similar Reads

  • JavaScript Design Patterns Tutorial
    Design patterns in Javascipt are communicating objects and classes that are customized to solve a general design problem in a particular context. Software design patterns are general, reusable solutions to common problems that arise during the design and development of software. They represent best
    8 min read
  • Creational Software Design Patterns in JavaScript

    • Builder Method | JavaScript Design Pattern
      The Builder design pattern is a creational design pattern used to construct complex objects by separating the construction process from the actual representation. It's especially useful when an object requires multiple steps or configurations to be created. Important Topics for the Builder Design Pa
      9 min read
    • Prototype Method - JavaScript Design Pattern
      A Prototype Method is a JavaScript design pattern where objects share a common prototype object, which contains shared methods. The prototype method allows you to reuse the properties and methods of the prototype object, and also add new ones as needed. The prototype method is useful for performance
      3 min read
    • Abstract Factory Pattern | JavaScript Design Patterns
      Abstract Factory Pattern is to abstract the process of object creation by defining a family of related factory methods, each responsible for creating a different type of object. These factory methods are organized within an abstract factory interface or class, and the client code uses this interface
      6 min read
    • Behavioural Software Design Patterns in JavaScript

      • Template Method | JavaScript Design Patterns
        Template Method is a behavioral design pattern that defines the skeleton of an algorithm in a base class while allowing subclasses to implement specific steps of the algorithm without changing its structure. It promotes code reusability and provides a way to enforce a consistent algorithm structure
        10 min read
      • State Method Design Patterns in JavaScript
        State method or State Design Patterns is a pattern that allows an object to alter its behavior when internal state changes occur. This pattern is used when an object wants to change its state dynamically. When we want to change behavior of object it internally uses if-else block to perform actions.
        4 min read
      • Iterator Method | JavaScript Design Pattern
        Iterator design pattern is a behavioral design pattern that provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. It separates the responsibility of accessing and traversing the elements from the aggregate object. This pattern is wi
        4 min read
      • Strategy Method | JavaScript Design Pattern
        Strategy Method or Strategy Pattern in JavaScript helps solve the problem of needing to use different methods or behaviors in your code and easily switch between them. Strategy Method is a behavioral design pattern in JavaScript that defines a family of algorithms, encapsulates each one, and makes t
        8 min read
      geeksforgeeks-footer-logo
      Corporate & Communications Address:
      A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
      Registered Address:
      K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
      GFG App on Play Store GFG App on App Store
      Advertise with us
      • Company
      • About Us
      • Legal
      • Privacy Policy
      • In Media
      • Contact Us
      • Advertise with us
      • GFG Corporate Solution
      • Placement Training Program
      • Languages
      • Python
      • Java
      • C++
      • PHP
      • GoLang
      • SQL
      • R Language
      • Android Tutorial
      • Tutorials Archive
      • DSA
      • Data Structures
      • Algorithms
      • DSA for Beginners
      • Basic DSA Problems
      • DSA Roadmap
      • Top 100 DSA Interview Problems
      • DSA Roadmap by Sandeep Jain
      • All Cheat Sheets
      • Data Science & ML
      • Data Science With Python
      • Data Science For Beginner
      • Machine Learning
      • ML Maths
      • Data Visualisation
      • Pandas
      • NumPy
      • NLP
      • Deep Learning
      • Web Technologies
      • HTML
      • CSS
      • JavaScript
      • TypeScript
      • ReactJS
      • NextJS
      • Bootstrap
      • Web Design
      • Python Tutorial
      • Python Programming Examples
      • Python Projects
      • Python Tkinter
      • Python Web Scraping
      • OpenCV Tutorial
      • Python Interview Question
      • Django
      • Computer Science
      • Operating Systems
      • Computer Network
      • Database Management System
      • Software Engineering
      • Digital Logic Design
      • Engineering Maths
      • Software Development
      • Software Testing
      • DevOps
      • Git
      • Linux
      • AWS
      • Docker
      • Kubernetes
      • Azure
      • GCP
      • DevOps Roadmap
      • System Design
      • High Level Design
      • Low Level Design
      • UML Diagrams
      • Interview Guide
      • Design Patterns
      • OOAD
      • System Design Bootcamp
      • Interview Questions
      • Inteview Preparation
      • Competitive Programming
      • Top DS or Algo for CP
      • Company-Wise Recruitment Process
      • Company-Wise Preparation
      • Aptitude Preparation
      • Puzzles
      • School Subjects
      • Mathematics
      • Physics
      • Chemistry
      • Biology
      • Social Science
      • English Grammar
      • Commerce
      • World GK
      • GeeksforGeeks Videos
      • DSA
      • Python
      • Java
      • C++
      • Web Development
      • Data Science
      • CS Subjects
      @GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
      We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
      Lightbox
      Improvement
      Suggest Changes
      Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
      geeksforgeeks-suggest-icon
      Create Improvement
      Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
      geeksforgeeks-improvement-icon
      Suggest Changes
      min 4 words, max Words Limit:1000

      Thank You!

      Your suggestions are valuable to us.

      What kind of Experience do you want to share?

      Interview Experiences
      Admission Experiences
      Career Journeys
      Work Experiences
      Campus Experiences
      Competitive Exam Experiences