Reading Time: 1 minutesMediator Design Pattern in Python
Mediator Design Pattern in Python
Design Patterns Home
What is it?
Mediator is an object which attempts to make two or more decoupled objects interact. The mediator handles the communication between different classes (or objects of the same class), which allows for zero (or little) dependency among them. The resultant decoupled code is easy to maintain. The Mediator Design Pattern is a Behavioral Pattern as it provides an industry-wide accepted method to handle communication between objects.
Why the need for it: Problem Statement
More often than not, a software solution is made up of numerous classes. During maintenance, while adding new classes, communication between classes may become intricate and make the code hard to read and even harder to maintain. In the Mediator Pattern, the mediator object is in charge of the communication, not allowing the objects to interact directly. This helps in lowering the inter-dependency, and easier to maintain code.
Terminology
- Mediator: An object which encapsulates communication between other objects. These objects interact with each other via the mediator.
How to implement it
A popular example to demonstrate the Mediator Pattern is Chat messaging. Users send each other messages with the chat room as the mediator.
def displayMessage( self , user, message): |
print ( "[{} says]: {}" . format (user, message)) |
def __init__( self , name): |
self .chatRoom = ChatRoom() |
def sendMessage( self , message): |
self .chatRoom.displayMessage( self , message) |
molly.sendMessage( "Hi Team! Meeting at 3 PM today." ) |
mark.sendMessage( "Roger that!" ) |
ethan.sendMessage( "Alright." ) |
[Molly says]: Hi Team! Meeting at 3 PM today. |
The above example is fairly primitive, but it suffices to illustrate the pattern. You can extend the code to portray a much more practical implementation.
See also: