Bỏ qua đến nội dung

SP7 - Bảo Vệ (Proxy) - Học Design Pattern Từ Những Thứ Đơn Giản

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.

Hoang Yell
Hoang Yell
4 phút đọc
English
SP7 - Bảo Vệ (Proxy) - Học Design Pattern Từ Những Thứ Đơn Giản

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.

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.

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.

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.

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

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:

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


Điều hướng series: Trước: SP6 - Object Pool (Flyweight) · Tiếp theo: BP1 - Gun (Iterator)

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