Moe's Tech Blog

[Design Pattern] Mediator Pattern 본문

Software Design Pattern/Notes

[Design Pattern] Mediator Pattern

moe12825 2022. 7. 2. 22:57
  • Facilitates communication between other components without them necessarily being aware of each other or having direct (reference) access to each other
  • Motivation for using it is:
    • 1. Some components may go in and out of a system at anytime
      • Example
        • 1. Chat room participants
        • 2. Customers on airplane
        • 3. Players on MMORPG (leave the game, suffer disconnection)
    • 2. Makes no sense for them to have a direct reference to one another
      • Those references can go dead at any time, and can't predict them
  • Solution: Have them all refer to some centeral components that facilitates communication

 

Example

  • 1. Chat room
    • is a component in the system where people can join and leave the chatroom, but they don't necessarily have to be aware of one another unless they are sending a direct message
class Person:
    def __init__(self, name):
        self.name = name
        self.chat_log = []
        self.room = None

    def receive(self, sender, message):
        s = f'{sender}: {message}'
        print(f'[{self.name}\'s chat session] {s}')
        self.chat_log.append(s)

    def say(self, message):
        self.room.broadcast(self.name, message)

    def private_message(self, who, message):
        self.room.message(self.name, who, message)


class ChatRoom:
    def __init__(self):
        self.people = []

    def broadcast(self, source, message):
        for p in self.people:
            if p.name != source:
                p.receive(source, message)


    def join(self, person):
        join_msg = f'{person.name} joins the chat'
        self.broadcast('room', join_msg)
        person.room = self
        self.people.append(person)


    def message(self, source, destination, message):
        for p in self.people:
            if p.name == destination:
                p.receive(source, message)


if __name__ == '__main__':
    room = ChatRoom()

    john = Person('John')
    jane = Person('Jane')

    room.join(john)
    room.join(jane)

    john.say('hi room')
    jane.say('oh, hey john')

    simon = Person('Simon')
    room.join(simon)
    simon.say('hi everyone!')

    jane.private_message('Simon', 'glad you could join us!')

 

References