A simple example of the proxy mode in the Python design mode and an example of the python Design Mode
This article describes the proxy mode of the Python design mode. We will share this with you for your reference. The details are as follows:
The proxy mode is generally a class function interface. Proxies can be interfaces of these things: network connections, stored objects, files, or other resources (expensive or not easy to copy ).
An example of a well-known proxy mode is the reference counting pointer object.
The proxy mode is an example of the structure design mode. This mode aims to create a proxy for a real object or class.
The proxy mode has three elements:
1. Real objects (objects that execute business logic and are proxies)
2. proxy class (an interface requested by the user to protect the real target)
3. User (obtain the user request of the task)
The proxy mode exists in the following situations:
① It is expensive to create an object for a real target class. It is cheap to create a simple object by a proxy class.
② Objects must be used directly by users.
③ When a request is made, creating an object for the actual target class may be delayed.
Use some real-world proxy examples, allapplabs and userpages to describe:
The cache proxy can cache the web pages requested by the user immediately. This method can avoid more repeated requests and improve performance.
The message box uses a progress bar to pass the program execution status.
Open a file with a text processing program and import a message saying, "please wait while the software opens the document"
A simple python implementation;
Let's think about a formal office scenario. In order to talk to the sales director of a company, the user first calls the receptionist in the sales director's office, and then the receptionist transfers the call. In this example, the sales lead is the target for the user to talk to, and the receptionist is an agent to protect the subject from the user's direct request to talk.
In the example of extension, we can think that 'sales authorization' is a real goal, creating a common target class as a manager, and the receptionist can inherit.
#coding=utf8import timeclass Manager(object): def work(self): pass def talk(self): passclass SalesManager(Manager): def work(self): print "Sales Manager working..." def talk(self): print "Sales Manager ready to talk"class Proxy(Manager): def __init__(self): self.busy = 'No' self.sales = None def work(self): print "Proxy checking for Sales Manager availability" if self.busy == 'Yes': self.sales = SalesManager() time.sleep(2) self.sales.talk() else: time.sleep(2) print "Sales Manager is busy"if __name__ == '__main__': p = Proxy() p.busy = 'Yes' p.work()
Running result: