Python设计模式——代理模式(Proxy)
代理模式(Proxy)
目的:代理模式用于需要给一个类增加一些调用方式,又不想改变其接口。常用于登录控制。
角色:
Real Sbuject: 被代理的类
Proxy: 代理
示例
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
本文来自博客园,作者:坦先生的AI资料室,转载请注明原文链接:https://www.cnblogs.com/yushengchn/p/16521941.html

浙公网安备 33010602011771号