23 design patterns (7) Java proxy pattern
23 design patterns Part 7: Java proxy pattern
definition:
Provide a proxy for other objects to control access to this object. In some cases, one object is not suitable or cannot directly reference another object, and the proxy object can act as an intermediary between the client and the target object
Role:
1. Abstract role: declare the common interface between real object and proxy object. 2. Proxy role: the proxy object role contains references to the real object, so that the real object can be operated. At the same time, the proxy object provides the same interface as the real object, so that it can replace the real object at any time. At the same time, the proxy object can attach other operations when performing real object operations, which is equivalent to encapsulating the real object. 3. Real role: the real object represented by the proxy role is the object we will eventually reference.
Classification:
Static proxy
Static agent means that the bytecode file of the agent class already exists before the program runs, and the relationship between the agent class and the delegate class is determined before the program runs.
Example:
Abstract roles, real objects and proxy objects share a common interface
Real role
delegable role
How to call his method after using the proxy?
Dynamic agent
The source code of the dynamic proxy class is dynamically generated by the JVM according to reflection and other mechanisms during the running of the program, so there is no bytecode file of the proxy class. The relationship between the agent role and the real role is determined when the program runs.
Example:
Abstract roles, real objects and proxy objects share a common interface
Real role
Agent role processor:
How to invoke (slightly different from static proxy)
advantage:
The business class only needs to pay attention to the business logic itself, which ensures the reusability of the business class. This is a common advantage of agents.
It can coordinate the caller and the callee, and reduce the coupling degree of the system to a certain extent.
Disadvantages:
Due to the addition of proxy objects between the client and the real subject, some types of proxy patterns may slow down the processing of requests, such as protecting the proxy.
The implementation of agent mode requires additional work, and the implementation process of some agent modes is more complex, such as remote agent.
Transferred from: Java confidant
The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.