×

Mediator Design Pattern with Python

Mediator Design Patterns Python Feature

Typically a Mediator is something that facilitates common ground for two communicating bodies. The same is with Mediator Pattern that suggests introducing a common interface in applications.

Consider the applications like a chat room, a real-time multiplayer game, or any system where the participant or the user can move in and out of the application at any point in time.

In this type of application keeping a direct reference, for communication, of two separate participants is useless because at a moment any participant can go offline. Hence it’s better, that all the communicating entities must communicate to a central authority.

That is what Mediator Design Pattern is- In case your application supports in and out movement of participants introduce a common communicating component or an interface.

A component that provides communication between other components without participants necessarily being aware of each other or having direct access to each other.

Members of Mediator Pattern

  • The Mediator: An interface for communicating with participant objects.
  • The participant: Entities that can move in and out.
  • ParticipantReference: Interface that keeps reference to the particpant objects. Implements the communication and transfer the messages between the participants.

Example

Let us implement a chat application where users can do group chats. Every user will be identified by its name and they can send and receive messages. The message sent by any user should be received by all the other users in the group.

  • The user class, keeping reference to the connected users, serving as ParticipantReference:
class User():
    def __init__(self, med, name):
        self.mediator = med
        self.name = name

    @abstractmethod
    def send(self, msg):
        pass

    @abstractmethod
    def receive(self, msg):
        pass
  • The Mediator:
class ChatMediator:
    def __init__(self):
        self.users = []

    def add_user(self, user):
        self.users.append(user)

    def send_message(self, msg, user):
        for u in self.users:
            if u != user:
                u.receive(msg)
  • Concrete implementation of user class (Participant):
class ConcreteUser(User):
    def send(self, msg):
        print(self.name + ": Sending Message: " + msg)
        self.mediator.send_message(msg, self)

    def receive(self, msg):
        print(self.name + ": Received Message: " + msg)
  • The Driver Code:
if __name__ == '__main__':
    mediator = ChatMediator()

    user1 = ConcreteUser(mediator, "John")
    user2 = ConcreteUser(mediator, "Harry")
    user3 = ConcreteUser(mediator, "Jack")
    user4 = ConcreteUser(mediator, "Tom")

    mediator.add_user(user1)
    mediator.add_user(user2)
    mediator.add_user(user3)
    mediator.add_user(user4)

    user1.send("Hello every one.")
Output
John: Sending Message: Hello every one.
Harry: Received Message: Hello every one.
Jack: Received Message: Hello every one.
Tom: Received Message: Hello every one.

A mediator is an object which attempts to make two or more decoupled objects interact. The Mediator Design Pattern is a Behavioral Pattern as it provides a method to handle communication between objects.