Mediator Method

Mediator Method

Mediator Method

The mediator method is a type of behavioural design pattern that allows you to reduce the unordered dependencies between the objects. This method helps mediator objects to communicate with each other and reduces coupling by reducing the dependencies between communicating objects. It works as a router between items, and it uses its own logic to provide a way of communication.

The mediator works with some component, and they are:

  • Colleague
    • it is the interface for communication with other colleagues
  • Concrete Colleague
    • it implements the colleague interface and communicates with colleagues through its mediator.
  • Concrete Mediator
    • it implements the mediator interface and coordinates the communication between colleague objects.
  • Mediator
    • it’s the interface for communication between colleague objects.
Implementation
# Mediator Class
class Course:
    def displayCourse(self, user, course_name):
        print("\n[{}'s course]: {}\n".format(user, course_name))

class User:
    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__':
    # Users object
    mark = User("Mark")
    ben = User("Ben")

    mark.sendCourse("Pentesting for Cybersecurity Professional")
    ben.sendCourse("Threat Hunting for Cybersecurity Professional")

Code Output:

ProBook:~/InfosecAddicts/$ python mediator.py

[Mark's course]: Pentesting for Cybersecurity Professional


[Ben's course]: Threat Hunting for Cybersecurity Professional

Pros and Cons

Pros
  • Inheritance is allowed
  • it reduces coupling between various components of a program.
  • It reuses individual components more quickly.
Cons
  • it converts into the god Object
  • it centralizes the control.
Lesson Content