Bỏ qua đến nội dung

BP5 - Quan Sát (Observer) - Học Design Pattern Từ Những Thứ Đơn Giản

Học sinh tự động phản ứng ngay khi cô giáo đổi trạng thái: cô ra ngoài thì tám chuyện, cô giảng bài thì tập trung. Học Observer bằng Python.

Hoang Yell
Hoang Yell
8 phút đọc
English
BP5 - Quan Sát (Observer) - Học Design Pattern Từ Những Thứ Đơn Giản

Observer là một mẫu thiết kế nhóm Behavioral: 🖤🖤🖤🖤🖤 (Độ hữu dụng trong Python: 5/5)

Observer là gì?

Observer thiết lập mối quan hệ một-nhiều (Teacher - Students): hễ một object thay đổi trạng thái (cô giáo ra ngoài hay bắt đầu giảng bài), tất cả các object đang theo dõi nó tự động nhận thông báo và phản ứng theo. Người ta còn hay gọi kiểu này là publish-subscribe.

Tại sao dùng Observer?

  • Tạo cơ chế đăng ký (attach / detach) để phát sự kiện cho nhiều bên nghe cùng lúc.
  • Tách rời hoàn toàn Teacher và từng loại Student: cô giáo chỉ biết danh sách Student qua interface chung chứ không cần biết chi tiết học sinh ngoan hay hư.
  • Dễ thêm/bớt người theo dõi lúc chạy mà không phải sửa code của Teacher.

Hỏi: Tôi ghét Observer, có cách nào khác không?

Đáp: Trong Python, bạn hiếm khi cần tạo cả class trừu tượng Student(ABC) chỉ để lắng nghe sự kiện. Lưu một list các callback function thuần (listeners.append(fn)) hoặc dùng thư viện signal như blinker là đủ tách rời mà bớt hẳn code thừa. (Còn nếu bạn phân vân State với Observer: State đổi hành vi nội tại của chính một object, còn Observer phát tín hiệu ra cho nhiều object bên ngoài.)

Khi nào dùng Observer?

Hỏi: Khi nào tôi dùng Observer?

Đáp: Khi bạn gặp những tình huống như:

  • Một object đổi trạng thái và nhiều object khác cần tự động cập nhật theo.
  • Muốn tránh phụ thuộc chặt giữa nguồn phát sự kiện và các bên lắng nghe.
  • Phát sự kiện (broadcast) cho các subscriber mà không cần biết trước có bao nhiêu subscriber đang nghe.

Đầu vào:

class Teacher:
    def __init__(self) -> None:
        self._state: str | None = None

    @property
    def state(self) -> str | None:
        return self._state

    @state.setter
    def state(self, value: str) -> None:
        self._state = value

    def act(self, action: str) -> None:
        """Change the state of the teacher."""
        self.state = action
        print(f"- TEACHER ACT: I'm {self.state}")


# A class that represents a bad student who gossips when the teacher goes out
class BadStudent:
   def react(self, teacher: Teacher) -> None:
       if teacher.state == "going out":
            print(f"  - BAD_STUDENT REACT: 😃 I'm gossiping in the class")
       else:
            print(f"  - BAD_STUDENT REACT: I don't care!")


# A class that represents a good student who focuses when the teacher speaks
class GoodStudent:
   def react(self, teacher: Teacher) -> None:
       if teacher.state == "speaking":
            print(f"  - GOOD_STUDENT REACT: 😃 I'm focusing on what the teacher says")
       else:
            print(f"  - GOOD_STUDENT REACT: I don't care!")

Kết quả mong muốn:

Teacher said: Hello new student '99' to my class
Teacher said: Hello new student '78' to my class
- TEACHER ACT: I'm replying husband's SMS
  - BAD_STUDENT REACT: I don't care!
  - GOOD_STUDENT REACT: I don't care!
- TEACHER ACT: I'm going out
  - BAD_STUDENT REACT: 😃 I'm gossiping in the class
  - GOOD_STUDENT REACT: I don't care!
- TEACHER ACT: I'm speaking
  - BAD_STUDENT REACT: I don't care!
  - GOOD_STUDENT REACT: 😃 I'm focusing on what the teacher says
Teacher said: GoodBye student '78'
- TEACHER ACT: I'm going out
  - GOOD_STUDENT REACT: I don't care!

Triển khai Observer:

Cách viết không dùng Observer:

# A class that represents a teacher who can change their state
class Teacher:
    def __init__(self) -> None:
        self._state: str | None = None

    @property
    def state(self) -> str | None:
        return self._state

    @state.setter
    def state(self, value: str) -> None:
        self._state = value

    def act(self, action: str) -> None:
        """Change the state of the teacher."""
        self.state = action
        print(f"- TEACHER ACT: I'm {self.state}")


# A class that represents a bad student who gossips when the teacher goes out
class BadStudent:
   def react(self, teacher: Teacher) -> None:
       if teacher.state == "going out":
            print(f"  - BAD_STUDENT REACT: 😃 I'm gossiping in the class")
       else:
            print(f"  - BAD_STUDENT REACT: I don't care!")


# A class that represents a good student who focuses when the teacher speaks
class GoodStudent:
   def react(self, teacher: Teacher) -> None:
       if teacher.state == "speaking":
            print(f"  - GOOD_STUDENT REACT: 😃 I'm focusing on what the teacher says")
       else:
            print(f"  - GOOD_STUDENT REACT: I don't care!")


if __name__ == "__main__":

    # Create a teacher and some students
    teacher = Teacher()
    bad_student = BadStudent()
    good_student = GoodStudent()

    # The teacher changes their state and the students react accordingly

    teacher.act("replying husband's SMS")
    bad_student.react(teacher)
    good_student.react(teacher)

    teacher.act("going out")
    bad_student.react(teacher)
    good_student.react(teacher)

    teacher.act("speaking")
    bad_student.react(teacher)
    good_student.react(teacher)

    teacher.act("going out")
    good_student.react(teacher)
  • Cách viết trên vi phạm nguyên tắc Open/Closed: mỗi lần thêm học sinh mới hay loại sự kiện mới, bạn phải đi sửa tay lại hàng loạt chỗ gọi bad_student.react(teacher), good_student.react(teacher) ở caller.
  • Ngoài ra caller bị coupled chặt với từng học sinh cụ thể (phải tự nhớ đứa nào còn trong lớp mà gọi .react()).
  • Dùng Observer tách rời Teacher khỏi từng loại Student thông qua interface chung, cho phép attach / detach bất kỳ lúc nào mà không sửa code của Teacher hay caller.

Cách viết dùng Observer:

from __future__ import annotations
from abc import ABC, abstractmethod


class Teacher:
    """A class that represents a teacher who can change their state and notify their students."""

    def __init__(self) -> None:
        self._state: str | None = None
        self._students: list[Student] = []

    @property
    def state(self) -> str | None:
        return self._state

    @state.setter
    def state(self, value: str) -> None:
        self._state = value

    @property
    def students(self) -> list[Student]:
        return self._students

    def attach(self, student: Student) -> None:
        """Add a new student to the list of observers."""
        print(f"Teacher said: Hello new student '{str(id(student))[-2:]}' to my class")
        self.students.append(student)

    def detach(self, student: Student) -> None:
        """Remove a student from the list of observers."""
        print(f"Teacher said: GoodBye student '{str(id(student))[-2:]}'")
        self.students.remove(student)

    def notify_students(self) -> None:
        """Notify all the students about the current state of the teacher."""
        print(f"- TEACHER ACT: I'm {self.state}")
        for student in self.students:
            student.react(self)

    def act(self, action: str) -> None:
        """Change the state of the teacher and notify the students."""
        self.state = action
        self.notify_students()


class Student(ABC):
    """An abstract class that represents a student who can react to a teacher's state."""

    @abstractmethod
    def react(self, teacher: Teacher) -> None:
        pass


class BadStudent(Student):
    """A class that represents a bad student who gossips when the teacher goes out."""

    def react(self, teacher: Teacher) -> None:
        if teacher.state == "going out":
            print(f"  - BAD_STUDENT REACT: 😃 I'm gossiping in the class")
        else:
            print(f"  - BAD_STUDENT REACT: I don't care!")


class GoodStudent(Student):
    """A class that represents a good student who focuses when the teacher speaks."""

    def react(self, teacher: Teacher) -> None:
        if teacher.state == "speaking":
            print(f"  - GOOD_STUDENT REACT: 😃 I'm focusing on what the teacher says")
        else:
            print(f"  - GOOD_STUDENT REACT: I don't care!")


if __name__ == "__main__":
    # Create a teacher object
    teacher = Teacher()

    # Create two student objects
    bad_student = BadStudent()
    good_student = GoodStudent()

    # Attach both students to observe the teacher
    teacher.attach(bad_student)
    teacher.attach(good_student)

    # Perform some actions as a teacher
    teacher.act("replying husband's SMS")
    teacher.act("going out")
    teacher.act("speaking")

    # Detach one student from observing the teacher
    teacher.detach(bad_student)

    # Perform another action as a teacher
    teacher.act("going out")

Điểm ăn tiền của bản Observer là:

  • Open/Closed: Thêm hoặc bỏ học sinh tự do mà không đụng vào Teacher hay vòng lặp gọi bên ngoài.
  • Loose coupling: Teacher chỉ nói chuyện với interface Student, hoàn toàn không biết BadStudent hay GoodStudent là ai.

Source Code


Điều hướng series: Trước: BP4 - Handling Chain · Tiếp theo: BP6 - State

Bài viết liên quan

yell@hoangyell:~ %

>hoangyell --status

Đang bận chở vợ con đi cafe & chơi với AI ☕🤖

Ủa ai réo Yell đấy? Cần tâm sự chuyện code hay collab thì ghé Instagram tui nè:

Ghé Instagram esc to close