代理模式和java動態代理

來源:互聯網
上載者:User

標籤:proxy.newproxyinstan   java動態代理   proxy   代理模式   

代理模式的作用及使用情境

使用代理模式的根本目的在於:如何在不直接操作對象的情況下,對此對象進行訪問?

常用的場合包括:1)消極式載入;2)在調用實際對象的方法前後加入某些商務邏輯(作用有點像spring的AOP)

類結構:



JAVA動態代理

JAVA提供了動態代理類以供使用者方便地實現代理模式

public interface Subject {public void doRequest();}public class SubjectImpl implements Subject {public void doRequest() {System.out.println("do some request");}}public class ProxyHandler implements InvocationHandler {private Object proxyObj;public ProxyHandler(Object proxy){this.proxyObj = proxy;}public Object invoke(Object proxy, Method method, Object[] args )throws Throwable {//do something before invokeSystem.out.println("do something before invoke");    //通過 method.invoke調用代理對象的方法    Object obj= method.invoke( proxyObj, args);      //do something after invokeSystem.out.println("do something after invoke");return obj;}}
調用代碼:

public class Client {public static void main(String[] args) {    SubjectImpl real = new SubjectImpl();       Subject proxySubject = (Subject)Proxy.newProxyInstance(Subject.class.getClassLoader(),     new Class[]{Subject.class}, new ProxyHandler(real));             proxySubject.doRequest();}}

輸出結果:


可見,在Client的main方法中,並沒有直接調用SubjectImpl對象的方法,使用java動態代理可以使我們少定義一個proxy實作類別

參考文章:

http://www.cnblogs.com/flyoung2008/archive/2013/08/11/3251148.html

代理模式和java動態代理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.