代理模式(Proxy Pattern)
代理模式是一种使用频率非常高的模式,在多个著名的开源软件和当前多个著名的互联网产品后台程序中都有所应用。下面我们用一个抽象化的简单例子,来说明代理模式。
In [2]:
info_struct=dict()
info_struct['addr']=10000
info_struct['content']=''
class Server(object):
content=''
def recv(self, info):
pass
def send(self, info):
pass
def show(self):
pass
class infoServer(Server):
def recv(self,info):
self.content=info
return 'recv OK!'
def send(self, info):
pass
def show(self):
print('SHOW:%s'%self.content)
infoServer有接收和发送的功能,发送功能由于暂时用不到,保留。另外新加一个接口show,用来展示服务器接收的内容。接收的数据格式必须如info_struct所示,服务器仅接受info_struct的content字段。那么,如何给这个服务器设置一个白名单,使得只有白名单里的地址可以访问服务器呢?修改Server结构是个方法,但这显然不符合软件设计原则中的单一职责原则。在此基础之上,使用代理,是个不错的方法。代理配置如下:
In [3]:
class serverProxy(object):
pass
class infoServerProxy(serverProxy):
server=''
def __init__(self,server):
self.server=server
def recv(self,info):
return self.server.recv(info)
def show(self):
self.server.show()
class WhiteInfoServerProxy(infoServerProxy):
whilte_list=[]
def recv(self,info):
try:
assert type(info)==dict
except:
return 'info structure is not correct'
addr = info.get('addr',0)
if not addr in self.whilte_list:
return 'Your address is not the white list'
else:
content=info.get('content','')
return self.server.recv(content)
def addWhite(self, addr):
self.whilte_list.append(addr)
def rmvWhite(self, addr):
self.whilte_list.remove(addr)
def clearWhite(self):
self.whilte_list=[]
In [4]:
info_struct=dict()
info_struct['addr']=10010
info_struct['content']='Hello World!'
info_server = infoServer()
info_server_proxy = WhiteInfoServerProxy(info_server)
print(info_server_proxy.recv(info_struct))
info_server_proxy.show()
info_server_proxy.addWhite(10010)
print(info_server_proxy.recv(info_struct))
info_server_proxy.show()