---
title: "BP8 - Điệp Viên Thăm Dò (Visitor) - Học Design Pattern Từ Những Thứ Đơn Giản"
description: "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."
pubDate: "2023-04-09"
lang: "vi"
slug: "bp8-visitor-learn-design-pattern-from-simple-things"
url: "https://hoangyell.com/vi/bp8-visitor-learn-design-pattern-from-simple-things/"
author: "HoangYell"
translation_en: "https://hoangyell.com/bp8-visitor-learn-design-pattern-from-simple-things/"
categories: ["Software Craft"]
tags: ["design-patterns", "behavioral-patterns"]
heroImage: "https://raw.githubusercontent.com/HoangGeek/store/main/webp/8X88Elf.webp"
---

_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.

![Image](https://raw.githubusercontent.com/HoangGeek/store/main/webp/230754864-306d6bf9-9a3c-4316-8466-60cdb71ea9d6.webp)

```markdy
scene duration=18 layout=LR width=1280 height=720
theme: light=doodle dark=nebula

user Loop "for location in locations:"
service Nuclear "NuclearFacility.accept(spy)"
service Military "MilitaryBase.accept(spy)"
service Spy "Spy (visit_nuclear_facility / visit_military_base)" icon=python
storage Diary "Sổ tay spy.diary"

beat dispatch "1. Double dispatch tự rẽ nhánh đúng loại":
  show $nodes stagger=50ms
  Loop -> Nuclear "accept(spy)"
  Nuclear -> Spy "spy.visit_nuclear_facility(self)"
  Loop -> Military "accept(spy)"
  Military -> Spy "spy.visit_military_base(self)"
  glow Spy color=#3b82f6

beat collect "2. Gom bí mật mà không sửa class địa điểm":
  Spy -> Diary "append(facility.secret / base.secret)"
  glow Diary color=#22c55e

player:
  playback:
    loop true
  controls:
    speed true
    speeds "0.25"
    interact true
    fullscreen true
    gif true
    theme true
  interaction:
    zoom true
    pan true
    click_to_play true
    double_click_to_reset true
    keyboard false
  chrome:
    badge true
    progress none
```

## 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._

![Image](https://raw.githubusercontent.com/HoangGeek/store/main/webp/rAq1NzB.webp)

## 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`.

```python
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:

```shell
[
    '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):

```python
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):

```python
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](https://github.com/HoangYell/Design-Pattern-From-Simple-Things/blob/main/bp8_visitor.py)

***

**Điều hướng series:** Trước: [BP7 - Template Method](https://hoangyell.com/vi/bp7-template-method-learn-design-pattern-from-simple-things/) · Tiếp theo: [BP9 - File History (Memento)](https://hoangyell.com/vi/bp9-file-history-learn-design-pattern-from-simple-things/)
