Mediator Pattern in Python
Mediator Pattern in Pythonを、編集してオンライン実行できる実践例で学びます。
Mediator Patternとは?
Mediator Pattern in Pythonを、編集してオンライン実行できる実践例で学びます。
どのような場面で使う?
- 実績のある構造を使って、繰り返し発生するオブジェクト設計の問題を解決します。
- 責務を分離し、コードを拡張・テストしやすくします。
- チームでアーキテクチャを議論するときに共通の設計用語を使います。
サンプルコード
main.py
class ChatRoom:
# Mediator: route colleague communication through a coordinator.
def send(self, sender, recipient, message):
# Coordinate communication between colleague objects.
recipient.receive(sender.name, message)
class User:
def __init__(self, name, room): self.name, self.room = name, room
def send(self, recipient, message): self.room.send(self, recipient, message)
def receive(self, sender, message): print(f"{self.name} from {sender}: {message}")
room = ChatRoom()
ada, lin = User("Ada", room), User("Lin", room)
ada.send(lin, "Hello")
期待される出力
Lin from Ada: Hello
仕組み
この例ではMediator Pattern in Pythonを説明します。入力値を変更してコードの動作を確認してください。
値を変更し、PythonをインストールせずにCodeUtilityオンラインPythonコンパイラで実行できます。
練習問題
入力値と境界ケースを変更し、より大きなデータでも動作を確認してください。
- パターンの構造を保ったまま、サンプルの対象領域を置き換えてください。
- パターンをより単純な実装と比較し、トレードオフを説明してください。
- 別の実装を追加する前に、各参加要素のテストを書いてください。