《Java編程思想》學習筆記6——Java動態代理__演算法

來源:互聯網
上載者:User

代理是一種常用的程式設計模式,如同網路代理程式一樣,代理是介於調用者和真正調用目標對象之間的中間對象,代理在調用真正目標對象時提供一些額外或者不同的操作,真正的對目標對象的操作還是通過代理調用目標對象來完成。

    簡單的代理例子如下: [java]  view plain copy //介面   interface Interface{       void doSomething();       void somethingElse(String arg);   }   //目標對象   class RealObject implement Interface{       public void doSomething(){           System.out.println(“RealObject doSomething”);   }   public void somethingElse(String arg){       System.out.println(“RealObject somethingElse ” + arg);   }   }   //簡單代理對象   class SimpleProxy implements Interface(       private Interface proxied;       public SimpleProxy(Interface proxied){           this.proxied = proxied;   }   public void doSomething(){       System.out.println(“SimpleProxy doSomething”);       proxied.doSomething();   }   public void somethingElse(String arg){       System.out.println(“SimpleProxy somethingElse ” + arg);       proxied.somethingElse(arg);   }   )   Class SimpleProxyDemo{       public static void consumer(Interface iface){           iface.doSomething();           iface.somethingElse(“TestProxy”);   }   public static void main(String[] args){   //不是用代理       cosumer(new RealObject());       //使用代理       cosumer(new SimpleProxy(new RealObject()));   }   }  

輸出結果為:

RealObject doSomething

RealObjectsomethingElse TestProxy

SimpleProxy doSomething

RealObject doSomething

SimpleProxy somethingElse TestProxy

RealObject somethingElse TestProxy

上面例子可以看出代理SimpleProxy在調用目標對象目標方法之前做了一些額外的操作。

Java中的代理是針對介面的動態代理,當然java也可以使用第三方的CGLIB實現針對類的代理,但是JDK中只支援針對介面的動態代理,我們只分析JDK的動態代理。

JDK動態代理的要素:

(1).實現了InvocationHandler的代理處理類,實現其invoke方法,該方法是代理調用目標對象方法以及提供額外操作的方法。

(2).使用Proxy.newProxyInstance(類載入器, 代理介面列表,InvocationHandler對象);方法建立實現了指定介面的動態代理。

JDK的代理例子如下: [java]  view plain copy //介面   interface Interface{       void doSomething();       void somethingElse(String arg);   }   //目標對象   class RealObject implement Interface{       

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.