Moe's Tech Blog
[Design Pattern] Mediator Pattern 본문
- 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)
- Example
- 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
- 1. Some components may go in and out of a system at anytime
- 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
- Design Patterns in Python, Dmitri Nesteruk: https://www.udemy.com/course/design-patterns-python/
'Software Design Pattern > Notes' 카테고리의 다른 글
[Design Pattern] Facade Pattern (0) | 2022.08.13 |
---|---|
[Design Pattern] Factory Pattern (0) | 2022.07.25 |
[OO Design Foundation] Object Oriented Modeling 2 (0) | 2022.07.13 |
[디자인 페턴] 싱글톤에 관하여 (0) | 2022.04.11 |
[디자인 페턴] 시작하며 (0) | 2022.03.20 |