forked from faif/python-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mediator.py
53 lines (36 loc) · 1.21 KB
/
mediator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
"""
https://www.djangospin.com/design-patterns-python/mediator/
Objects in a system communicate through a Mediator instead of directly with each other.
This reduces the dependencies between communicating objects, thereby reducing coupling.
*TL;DR
Encapsulates how a set of objects interact.
"""
from __future__ import annotations
class ChatRoom:
"""Mediator class"""
def display_message(self, user: User, message: str) -> None:
print(f"[{user} says]: {message}")
class User:
"""A class whose instances want to interact with each other"""
def __init__(self, name: str) -> None:
self.name = name
self.chat_room = ChatRoom()
def say(self, message: str) -> None:
self.chat_room.display_message(self, message)
def __str__(self) -> str:
return self.name
def main():
"""
>>> molly = User('Molly')
>>> mark = User('Mark')
>>> ethan = User('Ethan')
>>> molly.say("Hi Team! Meeting at 3 PM today.")
[Molly says]: Hi Team! Meeting at 3 PM today.
>>> mark.say("Roger that!")
[Mark says]: Roger that!
>>> ethan.say("Alright.")
[Ethan says]: Alright.
"""
if __name__ == "__main__":
import doctest
doctest.testmod()