faif / python-patterns

A collection of design patterns/idioms in Python
40.45k stars 6.94k forks source link

Mediator pattern is overcomplicated #272

Closed gyermolenko closed 5 years ago

gyermolenko commented 5 years ago

Looking through mediator pattern example I find it overcomplicated.

What I could get from it, in short:

I find it hard to follow and would like to hear opinion of another person.

To complare, I like the following example much more https://www.djangospin.com/design-patterns-python/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.
faif commented 5 years ago

Good suggestion. Go ahead, but please replace camel case method names with more Pythonic names (e.g. display_message)