A proxy pattern instance of Python design pattern

  • 2020-04-02 13:35:19
  • OfStack

The common way of over the wall is to use Proxy. The basic process is as follows:

The browser < -- > Proxy server < -- > The server

If the browser request does not reach the server, or the server is unable to respond to the browser, we can configure the browser request to be passed to the proxy server, which forwards the request to the server. The proxy server then passes the server's response content to the browser. Of course, when the proxy server gets the content of the request or response, it can also do some processing itself, such as caching the static content to speed up, or extracting the content of the request or response to do some proper or improper analysis. This over the wall approach is a concrete example of the Proxy Pattern in the design Pattern.

Wikipedia explains the proxy model as follows:


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.

The proxy pattern is based on process - oriented implementation

Here is a piece of process-oriented python code at the heart of the design pattern:


def hello():
    print 'hi, i am hello'
def proxy():
    print 'prepare....'
    hello()
    print 'finish....'
if __name__ == '__main__':
    proxy()

Operation results:

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

Did you think of decorators?


Proxy pattern based on object-oriented implementation


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

If the initialization function init of RealSubject has parameters, the proxy class ProxySubject can be modified in two ways: first, the init method of ProxySubject also has parameters, and the initialization parameters are passed to RealSubject when the proxy class is initialized. Second: change the init method of ProxySubject to:


def __init__(self):
    self.__rs = None

Change the request method of ProxySubject to:

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

Similar form of.


Related articles: