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
分类:
python设计模式系列
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南