Proxy mode
Decoupling of implementation logic and implementation of proxy mode
Proxy mode in order to provide additional operations, insert an object to replace the actual object. These operations typically involve communication with the actual object and the role of the agent acting as the middleman
/** * 接口 */public interface Interface { void doSomething(); void somethingElse(String arg);}
/** * 实际对象 */public class RealObject implements Interface { public void doSomething() { System.out.println("doSomething"); } public void somethingElse(String arg) { System.out.println("somethingElse" + arg); }}
/** * 代理对象 */public class Proxy implements Interface { private Interface proxied; public Proxy(Interface proxied) { this.proxied = proxied; } public void doSomething() { System.out.println("Proxy doSomething"); proxied.doSomething(); } public void somethingElse(String arg) { System.out.println("Proxy somethingElse" + arg); proxied.somethingElse(arg); }}
/** * 测试代理,比较原对象与代理对象 * * @param args */ public static void main(String[] args) { Interface iface = new RealObject(); iface.doSomething(); iface.somethingElse("bonobo"); Interface iface2 = new Proxy(iface); iface2.doSomething(); iface2.somethingElse("bonobo"); }
Dynamic Agent
The Java dynamic agent can dynamically create proxies and dynamically handle calls to the methods being proxied
All calls made in the dynamic are redirected to a single calling processor, and its job is to reveal the types of calls and determine the corresponding countermeasures
public class DynamicProxyHandler implements InvocationHandler { private Object proxied; public DynamicProxyHandler(Object proxied) { this.proxied = proxied; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("**** proxy:" + proxy.getClass() + ".method: " + method + ".args: " + args); if (args != null) { for (Object arg : args) { System.out.println(" " + args); } } return method.invoke(proxied, args); }}
public static void main(String[] args){ RealObject real = new RealObject(); real.doSomething(); real.somethingElse("bonobo"); Interface proxy = (Interface) Proxy.newProxyInstance( Interface.class.getClassLoader(), new Class[]{Interface.class}, new DynamicProxyHandler(real)); proxy.doSomething(); proxy.somethingElse("bonobo"); }
Java Proxy Mode