---
title: "SP7 - Bảo Vệ (Proxy) - Học Design Pattern Từ Những Thứ Đơn Giản"
description: "Sếp chặn mạng giờ làm việc để nhân viên tập trung. Đó chính là cách mẫu Proxy hoạt động: đứng giữa kiểm soát truy cập trước khi gọi object thật."
pubDate: "2023-05-21"
lang: "vi"
slug: "sp7-proxy-learn-design-pattern-from-simple-things"
url: "https://hoangyell.com/vi/sp7-proxy-learn-design-pattern-from-simple-things/"
author: "HoangYell"
translation_en: "https://hoangyell.com/sp7-proxy-learn-design-pattern-from-simple-things/"
categories: ["Software Craft"]
tags: ["design-patterns", "structural-patterns"]
heroImage: "https://raw.githubusercontent.com/HoangGeek/store/main/webp/photo-1611926653458-09294b3142bf.webp"
---

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

## Proxy là gì?

Proxy đặt một anh bảo vệ đứng ngay trước object thật với cùng một giao diện (`grant_access()`). Người gọi tưởng mình đang nói chuyện với `FreeInternetAccess`, trong khi `CompanyProxyInternetAccess` âm thầm kiểm tra điều kiện (hoặc trì hoãn khởi tạo, cache kết quả, ghi log) rồi mới chuyển tiếp yêu cầu vào trong.

![Image](https://raw.githubusercontent.com/HoangGeek/store/main/webp/1feb2b7b-e877-4dd5-90b2-d999ccf8ded8.webp)

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

user Staff "Nhân viên gọi grant_access()"
gateway Proxy "CompanyProxyInternetAccess (8:00-17:30)" icon=python
service Real "FreeInternetAccess (lazy-init)"

beat work "1. 09:00 sáng -> Chặn ngay tại Proxy":
  show $nodes stagger=50ms
  Staff -> Proxy "grant_access(09:00)"
  Staff <- Proxy "Cấm lướt web trong giờ làm!"
  glow Proxy color=#f59e0b

beat offhours "2. 07:00 sáng -> Khởi tạo lười & cho qua":
  Staff -> Proxy "grant_access(07:00)"
  Proxy -> Real "Chưa có thì khởi tạo rồi chuyển tiếp"
  Staff <- Real "Access granted!"
  glow Real 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 Proxy?
- **Kiểm soát hành vi mà không sửa class gốc**: Thêm xác thực/giới hạn giờ giấc (Protection Proxy), chỉ khởi tạo object nặng khi thực sự cần (Virtual Proxy), hoặc cache lời gọi tốn kém.
- **Đánh đổi**: Tăng thêm một bước trung gian và hơi rườm rà nếu interface gốc có hàng chục method (dù trong Python, `__getattr__` giúp proxy forward tự động các method còn lại khá dễ).

**Hỏi:** _Tôi ghét Proxy, có cách nào khác không?_

**Đáp:** _Nhét thẳng điều kiện kiểm tra vào trong class nếu đó là code của bạn, dùng `@decorator` cho function, hoặc thử AOP (`aspectlib`) nếu muốn can thiệp từ bên ngoài lúc runtime._

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

## Khi nào dùng Proxy?

**Hỏi:** _Khi nào thì nên dùng Proxy?_

**Đáp:** _Khi bạn cần kiểm soát quyền truy cập, lazy-load hoặc cache quanh một object mà vẫn giữ nguyên vẹn interface công khai của nó._

### Đầu vào:

Class `FreeInternetAccess` cho phép bất kỳ ai truy cập internet tự do.

```python
class FreeInternetAccess:
    def grant_access(self):
        print("Access granted. You can browse the free internet now!")
```

### Kết quả mong muốn:

Chặn quyền truy cập trong giờ làm việc hành chính dựa theo giờ hiện tại.

```shell
# FreeInternetAccess
Access granted. You can browse the free internet now!

# CompanyProxyInternetAccess
# current time is 7:00 AM
Access granted. You can browse the free internet now!
# current time is 9:00 AM
Sorry, access to the free internet is restricted during working hours!
```

## Triển khai Proxy:

### Cách viết không dùng Proxy (thử AOP với `aspectlib`):

Bạn có thể nhét thẳng logic vào class gốc hoặc nghịch AOP (`aspectlib`) để chèn aspect chặn lời gọi method từ ngoài. Cách này trông khá ngầu nhưng khó đọc và khó debug hơn Proxy thuần.

```python
import datetime
import aspectlib  # pip install aspectlib
from abc import ABC, abstractmethod

class InternetAccess(ABC):
    @abstractmethod
    def grant_access(self):
        pass

class FreeInternetAccess(InternetAccess):
    def grant_access(self):
        print("Access granted. You can browse the free internet now!")

@aspectlib.Aspect
def restrict_access(func, *args, **kwargs):
    current_time = datetime.datetime.now().time()
    start_time = datetime.time(8, 0)
    end_time = datetime.time(17, 30)
    if start_time <= current_time <= end_time:
        print("Sorry, access to the free internet is restricted during working hours!")
    else:
        yield aspectlib.Proceed

if __name__ == "__main__":
    # current time is 9:00 AM
    origin = FreeInternetAccess()
    origin.grant_access()
    try:
        aspectlib.weave(
            origin, restrict_access
        )  # apply the aspect to all methods of origin
        origin.grant_access()
    except StopIteration:
        pass
```

### Cách viết dùng Proxy:

```python
import datetime
from abc import ABC, abstractmethod

class InternetAccess(ABC):
    @abstractmethod
    def grant_access(self):
        pass

class FreeInternetAccess(InternetAccess):
    def grant_access(self):
        print("Access granted. You can browse the free internet now!")

class CompanyProxyInternetAccess(InternetAccess):
    def __init__(self):
        self.free_internet_access = None

    def grant_access(self, current_time=None):
        current_time = current_time or datetime.datetime.now().time()
        start_time = datetime.time(8, 0)
        end_time = datetime.time(17, 30)
        if start_time <= current_time <= end_time:
            print("Sorry, access to the free internet is restricted during working hours!")
        else:
            if self.free_internet_access is None:
                self.free_internet_access = FreeInternetAccess()
            self.free_internet_access.grant_access()

if __name__ == "__main__":
    origin = FreeInternetAccess()
    origin.grant_access()
    proxy = CompanyProxyInternetAccess()
    # Simulate 7:00 AM (allowed) and 9:00 AM (restricted)
    proxy.grant_access(datetime.time(7, 0))
    proxy.grant_access(datetime.time(9, 0))
```

Chú ý `CompanyProxyInternetAccess` kiêm luôn hai vai trò ở đây: vừa kiểm tra khung giờ (Protection Proxy), vừa chỉ khởi tạo `FreeInternetAccess()` khi thực sự được phép vào mạng (Virtual Proxy).

[Source Code](https://github.com/HoangYell/Design-Pattern-From-Simple-Things/blob/main/sp7_proxy.py)

***

**Điều hướng series:** Trước: [SP6 - Object Pool (Flyweight)](https://hoangyell.com/vi/sp6-object-pool-learn-design-pattern-from-simple-things/) · Tiếp theo: [BP1 - Gun (Iterator)](https://hoangyell.com/vi/bp1-gun-iterator-design-pattern-from-simple-things/)
