Python设计模式——代理模式(Proxy)

代理模式(Proxy)

目的:代理模式用于需要给一个类增加一些调用方式,又不想改变其接口。常用于登录控制。

角色:
Real Sbuject: 被代理的类
Proxy: 代理

返回 Python设计模式-outline

示例

from typing import Union


class Subject:
    """
    As mentioned in the document, interfaces of both RealSubject and Proxy should
    be the same, because the client should be able to use RealSubject or Proxy with
    no code change.

    Not all times this interface is necessary. The point is the client should be
    able to use RealSubject or Proxy interchangeably with no change in code.
    """

    def do_the_job(self, user: str) -> None:
        raise NotImplementedError()


class RealSubject(Subject):
    """
    This is the main job doer. External services like payment gateways can be a
    good example.
    """

    def do_the_job(self, user: str) -> None:
        print(f"I am doing the job for {user}")


class Proxy(Subject):
    def __init__(self) -> None:
        self._real_subject = RealSubject()

    def do_the_job(self, user: str) -> None:
        """
        logging and controlling access are some examples of proxy usages.
        """

        print(f"[log] Doing the job for {user} is requested.")

        if user == "admin":
            self._real_subject.do_the_job(user)
        else:
            print("[log] I can do the job just for `admins`.")


def client(job_doer: Union[RealSubject, Proxy], user: str) -> None:
    job_doer.do_the_job(user)


if __name__ == '__main__':    
    proxy = Proxy()

    real_subject = RealSubject()

    client(proxy, 'admin')
    # 预期输出
    # [log] Doing the job for admin is requested.
    # I am doing the job for admin

    client(proxy, 'anonymous')
    # 预期输出
    # [log] Doing the job for anonymous is requested.
    # [log] I can do the job just for `admins`.

    client(real_subject, 'admin')
    # 预期输出
    # I am doing the job for admin

    client(real_subject, 'anonymous')
    # 预期输出
    # I am doing the job for anonymous
posted @   坦先生的AI资料室  阅读(684)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示