The Orchestrator of Collaboration, Bringing Harmony to the Code
In essence, the Mediator Design Pattern transforms your code into a well-rehearsed orchestra, where objects collaborate seamlessly under the guidance of a central conductor. This promotes clarity, flexibility, and control in your program’s communication, ensuring a harmonious symphony of functionality.
from abc import ABC, abstractmethod
class Mediator(ABC):
@abstractmethod
def send_message(self, sender, message):
pass
class ChatMediator(Mediator):
def __init__(self):
self.users = []
def register_user(self, user):
self.users.append(user)
def send_message(self, sender, message):
for user in self.users:
if user != sender:
user.receive_message(sender, message)
class User:
def __init__(self, name, mediator):
self.name = name
self.mediator = mediator
mediator.register_user(self)
def send_message(self, message):
self.mediator.send_message(self, message)
def receive_message(self, sender, message):
print(f"{self.name} received message from {sender}: {message}")
# Client code using the Mediator pattern
mediator = ChatMediator()
john = User("John", mediator)
jane = User("Jane", mediator)
john.send_message("Hi Jane!")
# Output: Jane received message from John: Hi Jane!
jane.send_message("Hello John!")
# Output: John received message from Jane: Hello John!