Mediator

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Mediator 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.

class ChatRoom(object):
	'''Mediator class.'''
    def displayMessage(self, user, message):
        print("[{} says]: {}".format(user, message))

class User(object):
	'''A class whose instances want to interact with each other.'''
    def __init__(self, name):
        self.name = name
        self.chatRoom = ChatRoom()

    def sendMessage(self, message):
        self.chatRoom.displayMessage(self, message)

    def __str__(self):
        return self.name

molly = User('Molly')
mark = User('Mark')
ethan = User('Ethan')

molly.sendMessage("Hi Team! Meeting at 3 PM today.")
mark.sendMessage("Roger that!")
ethan.sendMessage("Alright.")

### OUTPUT ###
[Molly says]: Hi Team! Meeting at 3 PM today.
[Mark says]: Roger that!
[Ethan says]: Alright.

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:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply