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 @ 2022-07-26 17:47  坦先生的AI资料室  阅读(700)  评论(0)    收藏  举报