Python @ DjangoSpin

PyPro #99 Mediator Design Pattern

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

Write a Python program to implement Mediator Design Pattern.

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.

See also:

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

Leave a Reply