Design Pattern ใน Python

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

แบบฝึกหัด

ลองเปลี่ยน input และทดสอบกรณีขอบก่อนใช้ชุดข้อมูลที่ใหญ่ขึ้น

  1. เปลี่ยนโดเมนของตัวอย่างโดยยังคงโครงสร้างของแพตเทิร์นไว้
  2. เปรียบเทียบแพตเทิร์นกับการเขียนแบบที่ง่ายกว่าและอธิบายข้อแลกเปลี่ยน
  3. เขียนการทดสอบให้ผู้มีส่วนร่วมแต่ละส่วนก่อนเพิ่มการเขียนแบบอื่น
รันใน Python IDE →