標籤:ble his 額外 dos turn 中間 stat ret tcl
代理模式
代理模式 實現邏輯和實現的解耦
代理模式 為了提供額外的的操作,插入用來代替實際對象的對象。這些操作通常涉及與實際對象通訊,代理充當中間人的角色
/** * 介面 */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"); }
動態代理
Java動態代理可以動態建立代理並動態處理對所代理的方法的調用
在動態裡上所做的所有調用都會被重新導向到單一的調用處理器上,它的工作是揭示調用的類型並確定對應的對策
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 代理模式