Bỏ qua đến nội dung

BP8 - Điệp Viên Thăm Dò (Visitor) - Học Design Pattern Từ Những Thứ Đơn Giản

Một điệp viên ghé thăm các cơ sở tuyệt mật để thu thập thông tin mà không cần đụng sửa class gốc. Học mẫu Visitor và double dispatch trong Python.

Hoang Yell
Hoang Yell
5 phút đọc
English
BP8 - Điệp Viên Thăm Dò (Visitor) - Học Design Pattern Từ Những Thứ Đơn Giản

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

Visitor là gì?

Visitor tách thuật toán xử lý ra khỏi các class dữ liệu mà nó thao tác lên, giúp bạn thêm phép toán/hành vi mới mà không phải sửa code các class cũ.

Hình dung bạn có các địa điểm mật ở Triều Tiên như cơ sở hạt nhân (NuclearFacility) hay căn cứ quân sự (MilitaryBase). Bạn không thể sửa cấu trúc của chúng, nên bạn cử một Điệp viên (Spy) tới thăm từng nơi (accept(spy)). Địa điểm tự mở cửa báo danh với điệp viên qua double dispatch, còn điệp viên ghi chép bí mật vào sổ tay. Sau này muốn cử thêm kiểm toán viên hay đặc vụ phá hoại cũng chỉ cần viết class Visitor mới.

Tại sao dùng Visitor?

  • Thêm thao tác mới mà không chạm vào class cũ: Cử Spy, Auditor, hay Saboteur tới NuclearFacility và MilitaryBase mà không sửa một dòng nào trong hai class địa điểm.
  • Đánh đổi: Hễ thêm một subclass địa điểm mới là bạn phải cập nhật lại toàn bộ các class Visitor (thêm visit_*). Ngoài ra trong Python, Visitor vẫn chỉ đọc được các thuộc tính thông thường vì Python không khóa cứng private như Java/C++.

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

Đáp: Nếu bạn toàn quyền sửa các class dữ liệu và ít khi thêm thao tác mới, cứ viết thẳng method vào trong đó (như get_secret()). Còn nếu chỉ muốn phân nhánh theo kiểu dữ liệu trong Python mà lười viết trò accept(), dùng @functools.singledispatch gọn hơn nhiều.

Khi nào dùng Visitor?

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

Đáp: Khi bạn cần bổ sung liên tục nhiều hành vi mới lên một tập các class có sẵn nhưng không muốn (hoặc không được) sửa các class đó.

Đầu vào:

Hai địa điểm mật NuclearFacility và MilitaryBase, mỗi nơi giấu một secret.

from abc import ABC, abstractmethod


class NorthKorea(ABC):
    def __init__(self):
        self.secret = None

    @abstractmethod
    def accept(self, visitor):
        pass


class NuclearFacility(NorthKorea):
    def __init__(self):
        self.secret = "North Korea tests nuclear drones and builds uranium facility."

    def accept(self, visitor):
        visitor.visit_nuclear_facility(self)


class MilitaryBase(NorthKorea):
    def __init__(self):
        self.secret = "North Korea hides 16 missile bases and builds new one."

    def accept(self, visitor):
        visitor.visit_military_base(self)

Kết quả mong muốn:

Điệp viên ghé thăm hết các địa điểm và in ra nhật ký bí mật thu được:

[
    'North Korea tests nuclear drones and builds uranium facility.',
    'North Korea hides 16 missile bases and builds new one.'
]

Triển khai Visitor:

Cách viết không dùng Visitor (nhét method vào từng class):

from abc import abstractmethod


class NorthKorea:
    def __init__(self):
        self.secret = None

    @abstractmethod
    def get_secret(self):
        pass


class NuclearFacility(NorthKorea):
    def __init__(self):
        self.secret = "North Korea tests nuclear drones and builds uranium facility."

    def get_secret(self):
        return self.secret


class MilitaryBase(NorthKorea):
    def __init__(self):
        self.secret = "North Korea hides 16 missile bases and builds new one."

    def get_secret(self):
        return self.secret


class Spy:
    def __init__(self):
        self.diary = []

    def visit(self, location):
        self.diary.append(location.get_secret())


# Example usage
if __name__ == '__main__':
    locations = [NuclearFacility(), MilitaryBase()]
    spy = Spy()
    for location in locations:
        spy.visit(location)
    print(spy.diary)

Cách viết dùng Visitor (Double Dispatch):

from abc import ABC, abstractmethod


class NorthKorea(ABC):
    def __init__(self):
        self.secret = None

    @abstractmethod
    def accept(self, visitor):
        pass


class NuclearFacility(NorthKorea):
    def __init__(self):
        self.secret = "North Korea tests nuclear drones and builds uranium facility."

    def accept(self, visitor):
        visitor.visit_nuclear_facility(self)


class MilitaryBase(NorthKorea):
    def __init__(self):
        self.secret = "North Korea hides 16 missile bases and builds new one."

    def accept(self, visitor):
        visitor.visit_military_base(self)


class Spy:
    def __init__(self):
        self.diary = []

    def visit_nuclear_facility(self, facility):
        self.diary.append(facility.secret)

    def visit_military_base(self, base):
        self.diary.append(base.secret)


# Example usage
if __name__ == '__main__':
    locations = [NuclearFacility(), MilitaryBase()]
    spy = Spy()
    for location in locations:
        location.accept(spy)
    print(spy.diary)

Ghi chú Python: Nếu không muốn đặt tên thủ công từng visit_*, Python 3.8+ có sẵn @functools.singledispatchmethod để tự động điều hướng visit(self, location) theo đúng kiểu class.

Nhờ cơ chế double dispatch (location.accept(spy) -> spy.visit_<type>(self)), bạn tách hẳn logic thu thập bí mật ra khỏi các class địa điểm mà không cần dùng if isinstance(...) rườm rà.

Source Code


Điều hướng series: Trước: BP7 - Template Method · Tiếp theo: BP9 - File History (Memento)

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