代理模式
定义
为其他对象提供一种代理以控制这个对象的访问。
代理模式也叫做委托模式,是一种基本技巧。如状态模式、策略模式、访问者模式本质上是在更特殊的场景下采用了委托模式。
- Subject抽主题角色:抽象接口类
- RealSuject具体主题角色:业务逻辑的执行者
- Proxy代理角色:委托类,把抽象主题定义的方法委托给真实主题实现,并做预处理和善后处理工作
优点
- 职责清晰
- 高扩展性
- 智能化
Python实现
# -*- coding: UTF-8 -*-
import time
class SalesManager:
def talk(self):
print("Sales Manager ready to talk")
class Proxy:
def __init__(self):
self.busy = "No"
self.sales = None
def talk(self):
print("Proxy checking for Sales Manager availability")
if self.busy == "No":
self.sales = SalesManager()
time.sleep(0.1)
self.sales.talk()
else:
time.sleep(0.1)
print("Sales Manager is busy")
class NoTalkProxy(Proxy):
def talk(self):
print("Proxy checking for Sales Manager availability")
time.sleep(0.1)
print("This Sales manager will not talk to you, whether he is busy or not")
def main():
p = Proxy()
p.talk()
p.busy = "Yes"
p.talk()
p = NoTalkProxy()
p.talk()
if __name__ == '__main__':
main()