The Wayback Machine - https://web.archive.org/web/20241001104026/https://www.geeksforgeeks.org/mediator-method-python-design-pattern/
Open In App

Mediator Method – Python Design Pattern

Last Updated : 06 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Mediator Method is a Behavioral Design Pattern that allows us to reduce the unordered dependencies between the objects. In a mediator environment, objects take the help of mediator objects to communicate with each other. It reduces coupling by reducing the dependencies between communicating objects. The mediator works as a router between objects and it can have it’s own logic to provide a way of communication.

Design Components:

  • Mediator: It defines the interface for communication between colleague objects.
  • Concrete Mediator: It implements the mediator interface and coordinates communication between colleague objects.
  • Colleague: It defines the interface for communication with other colleagues
  • Concrete Colleague: It implements the colleague interface and communicates with other colleagues through its mediator.

Problem Without using Mediator Method

Imagine you are going to take admission in one of the elite courses offered by GeeksforGeeks such as DSA, SDE, and STL. Initially, there are very few students who are approaching to join these courses. Initially, the developer can create separate objects and classes for the connection between the students and the courses but as the courses become famous among students it becomes hard for developers to handle such a huge number of sub-classes and their objects.

Problem-Mediator-Method

Problem-Mediator-Method

Solution using Mediator Method

Now let us understand how a pro developer will handle such a situation using the Mediator design pattern. We can create a separate mediator class named as Course and a User Class using which we can create different objects of Course class. In the main method, we will create a separate object for each student and inside the User class, we will create the object for Course class which helps in preventing the unordered code.

Solution-Mediator-method

Solution-mediator-method

Python3
class Course(object):
    """Mediator class."""

    def displayCourse(self, user, course_name):
        print("[{}'s course ]: {}".format(user, course_name))


class User(object):
    '''A class whose instances want to interact with each other.'''

    def __init__(self, name):
        self.name = name
        self.course = Course()

    def sendCourse(self, course_name):
        self.course.displayCourse(self, course_name)

    def __str__(self):
        return self.name

"""main method"""

if __name__ == "__main__":

    mayank = User('Mayank')   # user object
    lakshya = User('Lakshya') # user object
    krishna = User('Krishna') # user object

    mayank.sendCourse("Data Structures and Algorithms")
    lakshya.sendCourse("Software Development Engineer")
    krishna.sendCourse("Standard Template Library")

UML Diagram

Following is the UML Diagram for Mediator Method:

Mediator-method-UML-Diagram

Mediator-method-UML-Diagram

Advantages

  • Single Responsibility Principle: Extracting the communications between the various components is possible under Mediator Method into a single place which is easier to maintain.
  • Open/Closed Principle: It’s easy to introduce new mediators without disturbing the existing client code.
  • Allows Inheritance: We can reuse the individual components of the mediators as it follows the Inheritance
  • Few Sub-Classes: Mediator limits the Sub-Classing as a mediator localizes the behavior that otherwise would be disturbed among the several objects.

Disadvantages

  • Centralization: It completely centralizes the control because the mediator pattern trades complexity of interaction for complexity in the mediator.
  • God Object: A Mediator can be converted into a God Object (an object that knows too much or does too much).
  • Increased Complexity: The structure of the mediator object may become too much complex if we put too much logic inside it.

Applicability

  • Reduce the number of sub-classes: When you have realized that you have created a lot of unnecessary sub-classes, then it is preferred to use the Mediator method to avoid these unnecessary sub-classes.
  • Air Traffic Controller: Air traffic controller is a great example of a mediator pattern where the airport control room works as a mediator for communication between different flights.

Further Read – Mediator Method in Java
 


Previous Article
Next Article

Similar Reads

Mediator Design Pattern in JavaScript | Design Pattern
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
5 min read
Mediator Design Pattern in Java
The mediator design pattern defines an object that encapsulates how a set of objects interact. The Mediator is a behavioral pattern (like the Observer or the Visitor pattern) because it can change the program's running behavior. We are used to see programs that are made up of a large number of classes. However, as more classes are added to a progra
4 min read
Mediator design pattern
The Mediator design pattern is a behavioral pattern that defines an object, the mediator, to centralize communication between various components or objects in a system. This promotes loose coupling by preventing direct interactions between components, instead of having them communicate through the mediator, facilitating better maintainability and f
7 min read
Mediator Design Pattern in C++
The Mediator Design Pattern in C++ is a behavioral pattern that defines an object, the mediator, to centralize communication between various components or objects in a system. This promotes loose coupling by preventing direct interactions between components, instead of having them communicate through the mediator, facilitating better maintainabilit
8 min read
Behavioral Design Pattern | JavaScript Design Pattern
Behavioral design patterns are a subset of design patterns in software engineering that deal with the interaction and responsibilities of objects. These patterns focus on how objects communicate and work together to achieve common tasks. Important Topics for the Behavioral Design Pattern in JavaScript Design Patterns Uses Cases of the Behavioral De
8 min read
Difference between Prototype Design Pattern and Flyweight Design Pattern
The major point in Prototype vs. Flyweight Design Pattern is that Prototype Design Pattern is a creational design pattern whereas Flyweight Design Pattern is a structural design pattern. In this post, we will look into this and more differences between the Prototype and Flyweight Design Patterns. Let us begin with a basic understanding of each of t
2 min read
Facade Design Pattern | JavaScript Design Pattern
Facade design pattern is a Structural design pattern that allows users to create a simple interface that hides the complex implementation details of the system making it easier to use. This pattern intends to create a simplified and unified interface for a set of interfaces hiding the implementation details making it less complex to use. Important
4 min read
Flyweight Design Pattern - JavaScript Design Pattern
The Flyweight Design Pattern is a structural design pattern used in JavaScript to minimize memory usage by sharing the data as much as possible with the related objects. Important Topics for Flyweight Design PatternDiagramatic Representation:Advantages of Flyweight design pattern:Disadvantages of Flyweight design pattern:The shared data typically c
4 min read
Difference Between Builder Design Pattern and Factory Design Pattern
Design patterns provide proven solutions to common problems in software design. The Builder and Factory patterns are two popular creational design patterns. The Builder pattern constructs complex objects step by step. In contrast, the Factory pattern creates objects without specifying their exact class. Both patterns streamline object creation but
7 min read
Strategy Method Design Pattern | C++ Design Patterns
Strategy Pattern is a behavioral design pattern that defines a family of interchangeable algorithms and allows them to be used interchangeably within a context. This pattern enables the algorithm to be selected at runtime, providing flexibility and promoting code reusability. Important Topics for the Strategy Method in C++ Design Patterns Example o
4 min read
State Method Design Pattern | C++ Design Patterns
In software design, managing the behavior of an object according to its internal state is a common issue. The state pattern addresses this issue by allowing an object to alter its behavior every time its internal state changes. This pattern encapsulates each state in a separate class, which makes it easier to add new states and modify existing stat
7 min read
Template Method Design Pattern | C++ Design Patterns
Template Method Pattern introduces a template in a superclass that defines the steps of an algorithm. These steps may include both common tasks shared among subclasses and specific tasks that need customization. Subclasses then implement or override these steps to modify the algorithm according to their specific needs. Important Topics for Template
7 min read
Why is Singleton Design Pattern is Considered an Anti-pattern?
Let us explore why the Singleton pattern, a popular way to ensure only one instance of a class exists, is now seen as problematic in software development. In this article, we will discuss drawbacks such as tight coupling between components, difficulty in unit testing, and issues with scalability in larger applications. Important Topics for Singleto
8 min read
Composite Design Pattern | JavaScript Design Patterns
The Composite Design pattern is a way of organizing objects. It helps us handle different objects in a similar way when they are put together to create a structure with parts and wholes. These parts and wholes are like building blocks that can be split into smaller pieces and then put together to make a tree-like structure. The composite design pat
6 min read
Memento Design Pattern | C++ Design Patterns
Memento Design Pattern is a behavioral design pattern that provides a mechanism for capturing an object's internal state and restoring it to that state at a later time. This pattern is useful when we need to implement features like undo/redo functionality or when we want to save and restore an object's state for various reasons. Important Topics fo
7 min read
Design Patterns Cheat Sheet - When to Use Which Design Pattern?
In system design, selecting the right design pattern is related to choosing the right tool for the job. It's essential for crafting scalable, maintainable, and efficient systems. Yet, among a lot of options, the decision can be difficult. This Design Patterns Cheat Sheet serves as a guide, helping you on the path toward optimal design pattern selec
7 min read
Accessing Web Resources using Factory Method Design Pattern in Python
A factory is a class for building other objects, where it creates and returns an object based on the passed parameters. Here, the client provides materials to the Factory class, and the Factory class creates and returns the products based on the given material. A Factory is not a design pattern, but it serves as a basis for the Factory Method Desig
4 min read
Implementing News Parser using Template Method Design Pattern in Python
While defining algorithms, programmers often neglect the importance of grouping the same methods of different algorithms. Normally, they define algorithms from start to end and repeat the same methods in every algorithm. This practice leads to code duplication and difficulties in code maintenance – even for a small logic change, the programmer has
4 min read
Prototype Method Design Pattern in Python
The Prototype Method Design Pattern in Python enables the creation of new objects by cloning existing ones, promoting efficient object creation and reducing overhead. This pattern is particularly useful when the cost of creating a new object is high and when an object's initial state or configuration is complex. By utilizing cloning, developers can
6 min read
Interpreter Method Design Pattern in Python
The Interpreter design pattern in Python is a behavioral design pattern that facilitates the interpretation and evaluation of expressions or language grammars. Important Topics to Understand Interpreter Method Design Pattern in Python What is the Interpreter Method Design Pattern in Python?Components of the Interpreter Design Pattern in PythonExamp
7 min read
Facade Method Design Pattern in Python
The Facade Method Design Pattern in Python simplifies complex systems by providing a unified interface to a set of interfaces in a subsystem. This pattern helps in reducing the dependencies between clients and the intricate system, making the code more modular and easier to understand. By implementing the Facade pattern, developers can hide the com
7 min read
Memento Method Design Pattern in Python
The Memento Design Pattern is a behavioral design pattern that allows you to capture and restore an object's state without revealing its internal structure. This pattern is particularly useful in implementing undo mechanisms. In this article, we will explore the Memento Method Design Pattern in Python, providing practical examples and use cases to
8 min read
Bridge Method | JavaScript Design Pattern
In software design, as systems grow and evolve, the complexity of their components can increase exponentially. This complexity often arises from the intertwining of different functionalities and features, making the system rigid, less maintainable, and harder to scale. The Bridge design pattern emerges as a solution to this problem, offering a way
9 min read
Memento Method - JavaScript Design Pattern
A behavioral design pattern in JavaScript called Memento focuses on externalizing and capturing an object's internal state so that it can later be restored. When you need to add features like undo/redo functionality, history tracking, or reverting an item to a former state, this pattern is quite helpful. Important Topics for the Memento MethodUnder
6 min read
Observer Method – JavaScript Design Pattern
Observer design pattern, a staple of behavioral design patterns in JavaScript, provides a means to establish a one-to-many relationship between objects. This design pattern is especially valuable for decoupling components and facilitating extensibility in software applications. By employing this pattern, you can have one object (the subject) notify
10 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 optimization, as it avoids creating new functions
3 min read
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 Pattern in JavaScript Design Pattern Example without
9 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 them interchangeable. It allows the client to choos
8 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 widely used in many programming languages, including
4 min read
Builder, Fluent Builder, and Faceted Builder Method Design Pattern in Java
Builder Pattern is defined as a creational design pattern that is used to construct a complex object step by step. It separates the construction of an object from its representation, allowing us to create different variations of an object with the same construction code. This pattern is particularly useful when dealing with a complex object with ma
8 min read