Original address: http://blog.csdn.net/xu__cg/article/details/52970885
First, Agent mode
Provides a proxy for an object that controls the access of the agent. The proxy class and the delegate class have a common parent or parent interface so that proxy class object overrides can be used wherever the delegate class object is used. The proxy class is responsible for the preprocessing of the request, filtering, assigning the request to the delegate class processing, and subsequent processing of the delegate class processing the request.
II. Structure of proxy mode
UML Class Diagrams:
The structure of the proxy mode is:
- abstract Role : a common interface between real objects and proxy objects.
- Proxy Role : The proxy object role contains a reference to the real object, allowing you to manipulate the real object while the proxy object provides the same interface as the real object to replace the real object at any moment. At the same time, the proxy object can attach other actions when performing the real object operation, which is equivalent to encapsulating the real object.
- Real role : The real object represented by the proxy role is the object we end up referencing.
Depending on the generation time of the proxy class, the agent can be divided into static agent and dynamic agent two kinds.
Third, static proxy
The source code of the proxy class is created by the programmer or tool, and then the proxy class is compiled. The so-called static is in the program before the existence of the proxy class of bytecode files, the relationship between the proxy class and the delegate class is determined before running.
Example code:
1. Abstract roles
public interface AbstractSubject { void doSomething();}
2. Proxy roles
public class ProxySubject implements AbstractSubject{ private AbstractSubject real ; public ProxySubject(AbstractSubject real) { this.real=real ; } @Override public void doSomething() { real.doSomething(); } public void doOtherthing() { }}
3. Real characters
public class RealSubject implements AbstractSubject{ @Override public void doSomething() { System.out.println( "真实角色被使用" ); }}
4. Client
public class Client { public static void main(String[] args ) { RealSubject real = new RealSubject(); ProxySubject proxy = new ProxySubject( real ); proxy.doSomething(); }}
5. Advantages and disadvantages of static proxies
Advantages: The business class only needs to focus on the business logic itself, ensuring the reusability of the business class. This is the common advantage of the agent.
Disadvantages:
- Proxy object of an interface to serve only one type of object, if you want to proxy a lot of methods, it is bound to be a proxy for each method, static agent in the program size is not competent when the larger.
- If an interface adds a method, all proxy classes need to implement this method in addition to all implementation classes that need to implement this method. Increases the complexity of code maintenance.
Four, dynamic agent
The source code for the
Dynamic proxy class is that the program is dynamically generated by the JVM during runtime based on mechanisms such as reflection, so there is no bytecode file for the proxy class. The relationship between the agent role and the real role is determined when the program runs.
1. First look at the dynamic agent-related javaapi
①. Java.lang.reflect.Proxy
This is the parent class of all proxy classes generated by the Java dynamic Agent mechanism, which provides a static set of methods for dynamically generating proxy classes and their objects for a set of interfaces. static method of the
proxy class:
//Method 1: The method is used to get the calling processor static invocationhandler getinvocationhandler (object proxy" //Method 2: This method is used to obtain class objects that are associated with a dynamic proxy class for a specified class loader and a set of interfaces static class getproxyclass (ClassLoader loader, class[] interfaces) //Method 3: This method is used to determine whether the specified class object is a dynamic proxy class static boolean Isproxyclass ( Span class= "Hljs-keyword" >class cl) //Method 4: This method is used to generate a dynamic proxy class instance for the specified class loader, a set of interfaces, and a calling processor static object newproxyinstance (ClassLoader loader, class[] interfaces, Invocationhandler h)
②.java.lang.reflect.invocationhandler
This is the call processor interface, which customizes an invoke method that centralizes the method invocation on the dynamic proxy class object, typically implementing proxy access to the delegate class in the method. Each time you generate a dynamic proxy class object, you specify a corresponding calling processor object.
Invocationhandler Core Approach
//该方法负责集中处理动态代理类上的所有方法调用。第一个参数既是代理类实例,第二个参数是被调用的方法对象 //第三个方法是调用参数。调用处理器根据这三个参数进行预处理或分派到委托类实例上反射执行 Object invoke(Object proxy, Method method,Object[] args )
③.java.lang.reflect.classloader
This is the class loader class, which is responsible for loading the bytecode of the class into the Java virtual machine (JVM) and defining the class object for that class before it can be used. Proxy static method generating dynamic proxy classes also need to be loaded through a class loader to use, and the only difference from the normal class is that its bytecode is generated dynamically by the JVM at runtime rather than pre-existing in any. class file. You need to specify a class loader object each time a dynamic proxy class object is generated.
2. Dynamic Agent Implementation steps
- Implement the Invocationhandler interface to create your own calling processor.
- Create a dynamic proxy class by providing an array of ClassLoader and proxy interface types to the proxy class.
- Perform real-world role-specific tasks.
Sample code
1. Abstract roles and real role codes are the same as above.
2. Create your own calling Processor:
Publicclass subjecthandler implements Span class= "Hljs-title" >invocationhandler{abstractsubject Real; public subjecthandler (Abstractsubject Real) {this.real=real; } @Override public Object invoke (Object obj, method method, object[] args) throws throwable {System.out.println ( "proxy class preprocessing Tasks"); //uses the reflection mechanism to assign the request to the delegate class processing. The Invoke method returns the object as the result of the methods execution. //because the sample program does not return a value, it ignores the return value processing Method.invoke (real, args); System.out.println ( "Agent-class follow-up tasks"); return null;}
3. Client:
public class Client { public static void main(String[] args) { RealSubject real=new RealSubject(); SubjectHandler handler=new SubjectHandler(real); //生成代理类对象 AbstractSubject proxy=(AbstractSubject) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{AbstractSubject.class},handler); proxy.doSomething(); }}
4. Advantages and disadvantages of dynamic agents
Advantages :
The biggest benefit of dynamic proxies compared to static proxies is that all methods declared in the interface are transferred to the calling processor in a centralized method (Invocationhandler.invoke). In this way, when the number of interface methods is more, we can be flexible processing, and do not need to act as a static proxy for each method to relay.
Insufficient :
Admittedly, the proxy has been designed to be very graceful, but there is a little bit of regret, that is, it has always been unable to get rid of the shackles only support interface agent, because its design doomed this regret. Recall the inheritance diagram of dynamically generated proxy classes, which are already destined to have a common parent class called Proxy. Java's inheritance mechanism is doomed to these dynamic proxy classes can not implement the dynamic proxy class, because the multi-inheritance in Java is inherently unworkable.
This article dynamic agent part of the content of a large citation: http://layznet.iteye.com/blog/1182924
Java design mode learning 06--static agent and dynamic agent (GO)