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

yipeiwu_com6年前Python基础

翻墙常用的方式就是使用代理(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()


运行结果:
复制代码 代码如下:

prepare....
hi, i am hello
finish....

有没有想到装饰器?


基于面向对象实现的代理模式

复制代码 代码如下:

class AbstractSubject(object):

    def __init__(self):
        pass

    def request(self):
        pass

class RealSubject(AbstractSubject):

    def __init__(self):
        pass
    def request(self):
        print 'hi, i am RealSubject'

class ProxySubject(AbstractSubject):

    def __init__(self):
        self.__rs = RealSubject()

    def request(self):
        self.__beforeRequest()
        self.__rs.request()
        self.__afterRequest()

    def __beforeRequest(self):
        print 'prepare....'

    def __afterRequest(self):
        print 'finish....'

if __name__ == '__main__':
    subject = ProxySubject()
    subject.request()

如果RealSubject的初始化函数init有参数,代理类ProxySubject可以作两种方式的修改: 第一种: ProxySubject的init方法同样也有参数,初始化代理类的时候将初始化参数传递给RealSubject。 第二种: 将ProxySubject的init方法改为:

复制代码 代码如下:

def __init__(self):
    self.__rs = None

将ProxySubject的request方法改为:
复制代码 代码如下:

def request(self, *args, **kwargs):
    if self.__rs == None:
        self.__rs = RealSubject(*args, **kwargs)
    self.__beforeRequest()
    self.__rs.request()
    self.__afterRequest()

的类似形式。

相关文章

批量将ppt转换为pdf的Python代码 只要27行!

这是一个Python脚本,能够批量地将微软Powerpoint文件(.ppt或者.pptx)转换为pdf格式。 使用说明 1、将这个脚本跟PPT文件放置在同一个文件夹下。 2、运行这个脚...

Python实现变声器功能(萝莉音御姐音)

Python实现变声器功能(萝莉音御姐音)

登录百度AL开发平台 在控制台选择语音合成 创建应用 填写应用信息 在应用列表获取(Appid、API Key、Secret Key) 6. 安装pythonsdk 安装使用P...

使用Python将字符串转换为格式化的日期时间字符串

我正在尝试将字符串“20091229050936”转换为“2009年12月29日(UTC)” >>>import time >>>s = time...

python进阶教程之异常处理

在项目开发中,异常处理是不可或缺的。异常处理帮助人们debug,通过更加丰富的信息,让人们更容易找到bug的所在。异常处理还可以提高程序的容错性。 我们之前在讲循环对象的时候,曾提到一个...

使用Python发送各种形式的邮件的方法汇总

我们平时需要使用 Python 发送各类邮件,这个需求怎么来实现?答案其实很简单,smtplib 和 email 库可以帮忙实现这个需求。smtplib 和 email 的组合可以用来发...