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()

的类似形式。

相关文章

python读csv文件时指定行为表头或无表头的方法

python读csv文件时指定行为表头或无表头的方法

pd.read_csv()方法中header参数,默认为0,标签为0(即第1行)的行为表头。若设置为-1,则无表头。示例如下: (1)不设置header参数(默认)时: df1 =...

详解Python中的分组函数groupby和itertools)

具体代码如下所示: from operator import itemgetter #itemgetter用来去dict中的key,省去了使用lambda函数 from iterto...

Python用Bottle轻量级框架进行Web开发

Python用Bottle轻量级框架进行Web开发

当前Python Web开发中的框架算Django最为流行了,但是本文介绍的是一个较为轻量级的Web框架:Bottle框架。理论性的东西就不讲了,直接上实例代码。 1.问题描述 &nbs...

Python通过OpenCV的findContours获取轮廓并切割实例

1 获取轮廓 OpenCV2获取轮廓主要是用cv2.findContours import numpy as np import cv2 im = cv2.imread('test...

详解Python实现多进程异步事件驱动引擎

详解Python实现多进程异步事件驱动引擎

本文介绍了详解Python实现多进程异步事件驱动引擎,分享给大家,具体如下: 多进程异步事件驱动逻辑 逻辑 code # -*- coding: utf-8 -*- ''' a...