Core idea
Proxy Pattern is a structural design mode to provide an agent object for objects to control access to target objects. The proxy mode can add additional functions to the target object without changing the code of the target object.
structure
- Abstract theme (Subject)
Define the universal interface of the proxy object and the target object, so that the proxy object can replace the target object. - Real Subject
The object of real business logic, the client finally wants to access the goal. - Proxy (proxy)
Control the interview with real themes, responsible for interacting with the real theme, can add additional functions.
Proxy mode classification
Static agent
Dynamic agent
Jdk dynamic proxy
Code implementation:
package .structural_patterns.proxy.jdk_proxy;
import ;
import ;
import ;
public class ProxyFactory {
Private object target;
Public ProxyFactory (Object Target) {
= target;
}
public object getProxyObject () {) {) {)
Return (Return (
() .GetClassLoader (),
() .getInterface (),,,,
New Invocationhandler () {
@Override
Public Object Invoke (Object Proxy, Method Method, Object [] ARGS) Throws Throwable {
("Collection of a certain fee"););
Return (target, args);
}
}
);
}
}
principle:
The core of the dynamic proxy is to dynamically generate proxy classes and load them to memory. Its execution process is as follows:
Proxy object creation
Classloader Loader, Class <?> [] Interfaces, Invocationhandler H) method::
Loader: Specify the class loader for loading the proxy class generated by dynamic generation.
interfaces: Specify interfaces that need to be implemented by the proxy class.
H: The call processor of the proxy object realizes the InvoCATIONHANDLER interface.
Generate the bytecode of the proxy class
The JDK dynamic agency will dynamically generate agent class (bytecode) during runtime. These proxy classes inherit from proxy and achieve all interfaces of the target object.
Proxy class load
The dynamic proxy class is loaded into the JVM through the specified class loader.
Method call processing
When calling the method of the proxy object, the actual trigger () method is actually triggered:
Pass the information of the target method (including method objects and parameters) to Invoke ().
In the INVOKE () method, developers can customize logic (such as permissions verification, log records, etc.).
If you need to call the target object, execute it by reflection.
CGLIB dynamic proxy
Realization process:
package .structural_patterns.proxy.cglib_proxy;
import ;
import ;
import ;
import ;
public class ProxyFactory implements MethodInterceptor {
Private object target;
Public ProxyFactory (Object Target) {
= target;
}
public object getProxyinstance () {
// 1. Create an enhancer object
Enhancer enhancer = new enhancer ();
// 2. Set parent class
(());
// 3. Set the callback function
(this);
// 4. Create proxy objects and return
Return ();
}
@Override
Public Object Internet (Object O, Method Method, Object [] Objects, MethodProxy MethodProxy) Throws Throwable {
("Agent Point Collection of Agent Fee");
// The method of calling the target object
Object obj = (o, objects);
Return obj;
}
}
principle:
Based on the inheritance of the proxy
CGLIB will inherit the target class and generate a subclass of a target class as the proxy class.
The subclass will rewrite all the non -final methods of the target class (final method cannot be inherited or represented).
Method calls will be intercepted by the agent class, and the proxy logic is achieved through the MethodInterceptor.
Bytecode generation
CGLIB uses ASM framework to operate byte code, dynamically generates the .class file of the proxy class, and load it to JVM.
Enhancer is the core category of CGLIB, which is used to generate proxy classes.
The agency class will be dynamically loaded into the memory during runtime instead of compiling in advance.
Method interception
The method of the proxy method is intercepted and is handled by the intercept method of the MethodInterceptor interface.
Enhanced logic can be added in the intercept method to determine whether the target class is called (through MethodProxy).
Method call
If the method of the target class is required, the parent class method will be directly called to avoid using reflex calls, and the performance is high.
The difference between JDK dynamic proxy and CGLIB
characteristic
Jdk dynamic proxy
CGLIB dynamic proxy
Whether the interface is required
The interface must be implemented
No interface, directly proxy
Way of implementation
Based on reflex generation proxy
Based by bytecode operation to generate childcare
performance
Low, dependent reflection (faster after 1.8)
High, call the byte code directly
Use scene
The target class has interface
Target class has no interface or high performance requirements
limit
The target class must implement the interface
The target category cannot be finia
Applicable scenario
Delay initialization (virtual agent). If you have an occasional heavyweight service object, you can use the proxy mode when maintaining the operation of the object.
You do not need to create the object when the program starts, which can delay the initialization of the object to the time when it is really needed.
Access control (protection agent). If you only want to use a service object for specific clients, the object here can be a very important part of the operating system, and the client is a variety of startup programs (including malicious procedures). At this time, the proxy mode can be used.
The proxy can pass the request to the service object when the client certificate meets the requirements.
Remote service (remote agent). It is suitable for the situation where the service object is located on the remote server.
In this case, the agent passes the client request through the network to handle all complex details related to the network.
Record log request (log record agent). It is suitable for historical records when you need to save the request for service objects.
The proxy can record before the request for transmission of the service.
The cache request results (cache proxy). It is suitable for the request of cache customer request results and managed the cache life cycle, especially when the volume of the return result is very large.
The agent can cache the same results required for repeated requests, and can also use the request parameter as the key value of the index cache.
Smart reference. The object was immediately destroyed when no client used a certain heavyweight object.
The agency records all clients that have obtained the service object or the result. The agency traverses various clients from time to time to check whether they are still running. If the corresponding client list is empty, the agent will destroy the service object and release the underlying system resources.
The agent can also record whether the client has modified the service object. Other clients can also be reused an unmodified object.
Advantages and disadvantages
advantage:
Separation of responsibilities: The agency class is responsible for the expansion function, and the real class focuses on the core business logic.
The principle of opening and closing: It can enhance the function without modifying the real object.
Improve system security: access to real objects through proxy control.
shortcoming:
Increase system complexity
The relationship with other models
The adapter mode can provide different interfaces for the encapsulated object. The proxy mode can provide the same interface for the object, while the decorative mode can provide an interface for the object.
The similarities between the appearance pattern and the agent are that they cached a complex entity and initialized it by itself. The proxy and its service object follow the same connection, so that it can be exchanged with the service target, which is different from the appearance at this point.
Decoration and proxy have similar structures, but their intentions are very different. The construction of these two modes is based on the combination principle, which means that one object should assign some work to another. The difference between the two is that the agent usually manages the life cycle of its service object, and the generation of decoration is always controlled by the client.