Python设计模式之代理模式实例

1071次阅读  |  发布于5年以前

翻墙常用的方式就是使用代理(Proxy),其基本过程如下:

浏览器<-->代理服务器<-->服务器

如果浏览器请求不到服务器,或者服务器无法响应浏览器,我们可以设定将浏览器的请求传递给代理服务器,代理服务器将请求转发给服务器。然后,代理服务器将服务器的响应内容传递给浏览器。当然,代理服务器在得到请求或者响应内容的时候,本身也可以做些处理,例如缓存静态内容以加速,或者说提取请求内容或者响应内容做些正当或者不正当的分析。这种翻墙方式,就是设计模式中代理模式(Proxy Pattern)的一个具体例子。

维基百科对代理模式做了以下解释:

复制代码 代码如下:

In computer programming, the proxy pattern is a software design pattern. A proxy, in its most general form, is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.

基于面向过程实现的代理模式

下面是一段体现该设计模式中心的面向过程的python代码:

复制代码 代码如下:

def hello():
print 'hi, i am hello'

def proxy():
print 'prepare....'
hello()
print 'finish....'

if name == 'main':
proxy()

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8