1. 意圖:
為其他對象提供一種代理以控制對這個對象的訪問
2. 別名:
surrogate替身
3. 動機
按需創建, 替代對象
4. 適用性
* 遠程代理
* 虛代理
* 保護代理
* 智能指引
5. 結構
6. 實例
package net.yeah.fanyamin.pattern.proxy; /** * @author walter */ interface Greet { void sayHello(String name); void goodBye(); } class GreetImpl implements Greet { public void sayHello(String name) { System.out.println("Hello " + name); } public void goodBye() { System.out.println("Good bye."); } } public class SimpleProxy implements Greet { private Greet greet = null; SimpleProxy(Greet greet) { this.greet = greet; } public void sayHello(String name) { System.out.println("--before method sayHello"); greet.sayHello(name); System.out.println("--after method sayHello"); } public void goodBye() { System.out.println("--before method goodBye"); greet.goodBye(); System.out.println("--after method goodBye"); } /** * @param args */ public static void main(String[] args) { Greet greet = new SimpleProxy(new GreetImpl()); greet.sayHello("walter"); greet.goodBye(); } }
?利用JDK中的動態代理
/** * */ package net.yeah.fanyamin.pattern.proxy; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * @author walter */ public class DebugProxy implements java.lang.reflect.InvocationHandler { private Object obj; public static Object newInstance(Object obj) { return java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new DebugProxy(obj)); } private DebugProxy(Object obj) { this.obj = obj; } public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { Object result; try { System.out.println("--before method " + m.getName()); result = m.invoke(obj, args); } catch (InvocationTargetException e) { throw e.getTargetException(); } catch (Exception e) { throw new RuntimeException("unexpected invocation exception: " + e.getMessage()); } finally { System.out.println("--after method " + m.getName()); } return result; } /** * @param args */ public static void main(String[] args) { Greet greet = (Greet) DebugProxy.newInstance(new GreetImpl()); greet.sayHello("walter"); greet.goodBye(); } }
?
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
