This article mainly introduces the Proxy mode Python instance in the design mode. If you need a friend, you can refer to the common method of turning over the wall is to use Proxy. The basic process is as follows:
Browser <--> proxy server <--> Server
If the browser request does not reach the server, or the server cannot respond to the browser, we can set to pass the browser request to the proxy server, the proxy server will forward the request to the server. Then, the proxy server passes the server response content to the browser. Of course, when the proxy server receives a request or response content, it can also do some processing, such as caching static content to accelerate, or extract the request content or response content for legitimate or improper analysis. This method is a specific example of Proxy Pattern in the design mode.
Wikipedia has explained the proxy mode as follows:
The Code is 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 cocould interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.
Process-oriented proxy Mode
The following is a python code that reflects the process-oriented design mode center:
The Code is as follows:
Def hello ():
Print 'Hi, I am hello'
Def proxy ():
Print 'Prepare ....'
Hello ()
Print 'finish ....'
If _ name _ = '_ main __':
Proxy ()
Running result:
The Code is as follows:
Prepare ....
Hi, I am hello
Finish ....
Did you think of a decorator?
Object-oriented proxy Mode
The Code is as follows:
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 realsubobject'
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 RealSubject initialization function init has parameters, the proxy class ProxySubject can be modified in two ways: the first one: The init method of ProxySubject also has parameters, during the initialization of the proxy class, the initialization parameters are passed to RealSubject. Method 2: Change the init method of ProxySubject:
The Code is as follows:
Def _ init _ (self ):
Self. _ rs = None
Change the request Method of ProxySubject:
The Code is as follows:
Def request (self, * args, ** kwargs ):
If self. _ rs = None:
Self. _ rs = RealSubject (* args, ** kwargs)
Self. _ beforeRequest ()
Self. _ rs. request ()
Self. _ afterRequest ()
.