1. The three elements proxy mode
Acting this model is not uncommon in our lives, to cattle on behalf of the ticket, wearing hospital registration, and even brokers, lawyers and so on are professional agent
But no matter what kind of proxy, in fact, they are inseparable from the three elements
a. the principal b. Acting transaction c. Attorney
Acting in 2.java
Abstract to java, there are two objects (the agent and the principal) and a interface method (agent transaction) only
Code Example:
First, create a proxy object ProxyDemo
. 1 Package com.pl.demo; 2 . 3 Import java.lang.reflect.InvocationHandler; . 4 Import the java.lang.reflect.Method; . 5 . 6 / ** . 7 * @AutLhor: Mr.P . 8 * @date: 2019/10 / 26 is . 9 * @time: 11:30 10 * / . 11 public class ProxyDemo the implements of InvocationHandler { 12 is Private Object Object; // the real role of the agent, the proxy object holds a 13 is 14 public ProxyDemo (Object Object) { 15 the this .Object = Object; 16 } 17 // second parameter is an excuse method is implemented in the proxy object, the third parameter is the parameter interface method proxy object 18 is @Override . 19 public Object Invoke (Object Proxy, Method, Method, Object [] args) throws {throwable 20 is System.out.println ( "pre-operation" ); 21 is for (Object Object: args) { 22 is System.out.println (Object); 23 is } 24 Object Invoke = Method.invoke (Object, args); 25 System.out.println ( "post-operation" ); 26 is return Invoke; 27 } 28 } 29
Second, is to create a proxy object
. 1 List Client = new new the ArrayList (); // interface defines the method requires agent, a step of: generating the proxy object, two steps: the stresses transmitted to the proxy object proxy object Step three: Method proxy object complete Agent
Finally, create an interface
For easy operation, where the interface directly java the List interface
. 1 public class Client { 2 public static void main (String [] args) { . 3 List Client = new new the ArrayList (); // interface defines the method requires agent, a step of: generating the proxy object, two steps: the speaking the proxy object to the proxy object step three: method completion agent proxy object . 4 .. = proxy List (List) the Proxy.newProxyInstance (client.getClass () getClassLoader (), client.getClass () The getInterfaces (), new new ProxyDemo (Client) ); // the first parameter is obtained by proxy object class loader, the second parameter is the index obtained by the interface proxy object, the proxy object third-defined parameters . 5 proxy.add ( "John Doe" ) ; 6 } 7 }