Welcome to our Python tutorial on the Mediator Pattern! In this lesson, we'll explore a behavioral design pattern that simplifies communication between complex systems by introducing an intermediary (the mediator) to manage the interaction between them. 💡 Pro Tip: The Mediator Pattern is particularly useful in situations where multiple objects have complex relationships.
<a name="introduction"></a>
The Mediator Pattern is a behavioral design pattern that encapsulates the interaction between objects, simplifying the communication between them and reducing their complexity. By introducing a mediator, we can make the system easier to maintain, modify, and test.
<a name="why-use"></a>
There are several reasons to use the Mediator Pattern:
<a name="design"></a>
To design the Mediator Pattern in Python, we'll follow these steps:
Colleague abstract base class, which will be the base for all objects that interact with each other.Mediator abstract base class, which will handle the communication between Colleagues.Colleague and Mediator classes, which will define the specific interactions between objects.# Abstract base class for Colleagues
class Colleague:
def __init__(self, mediator):
self.mediator = mediator
# Abstract base class for Mediators
class Mediator:
def __init__(self):
self.colleagues = []
def add_colleague(self, colleague):
self.colleagues.append(colleague)
# Implement other methods here<a name="real-world"></a>
Let's consider a multi-user chat system as a real-world example. In this system, users can send messages to each other, and the system must manage the communication between them.
User class, which inherits from the Colleague abstract base class.ChatSystem class, which inherits from the Mediator abstract base class.ChatSystem class to handle user messages, such as send_message and receive_message.class User(Colleague):
def __init__(self, name, chat_system):
super().__init__(chat_system)
self.name = name
chat_system.add_colleague(self)
class ChatSystem(Mediator):
def send_message(self, sender, message):
for colleague in self.colleagues:
if colleague != sender:
colleague.receive(sender, message)
def receive(self, sender, message):
print(f"{self.name} received a message from {sender}: {message}")
alice = User("Alice", chat_system)
bob = User("Bob", chat_system)
alice_message = "Hi Bob, how are you?"
bob_message = "I'm doing well, Alice. How about you?"
alice.send_message(bob, alice_message)
bob.send_message(alice, bob_message)<a name="implementation"></a>
In this example, we've implemented the Mediator Pattern in Python to create a simple multi-user chat system. The User class represents each user, and the ChatSystem class acts as the mediator, handling the communication between users.
<a name="quiz"></a>
What is the main purpose of the Mediator Pattern in Python?