【ThinkingInJava】33、動態代理機制,thinkinginjava33

來源:互聯網
上載者:User

【ThinkingInJava】33、動態代理機制,thinkinginjava33

/*** 書本:《Thinking In Java》* 功能:動態代理機制* 檔案:SimpleProxyDemo.java* 時間:2015年4月15日21:41:39* 作者:cutter_point*/package Lesson14TypeInformation;import static net.mindview.util.Print.*;interface Interface{//一個介面提供兩個方法void doSomething();void somethingElse(String arg);}class RealObject implements Interface{//實現介面@Overridepublic void doSomething() {print("doSomething");}@Overridepublic void somethingElse(String arg) {print("somthingElse " + arg);}}class SimpleProxy implements Interface{//實現兩個介面之後,在加上了一個變數private Interface proxied;public SimpleProxy(Interface proxied){this.proxied = proxied;}public void doSomething() {    print("SimpleProxy doSomething");//先實現自己的功能,然後調用傳進來的這個介面的功能    proxied.doSomething();}  public void somethingElse(String arg)   {    print("SimpleProxy somethingElse " + arg);    proxied.somethingElse(arg);  }}public class SimpleProxyDemo {public static void consumer(Interface iface) {    iface.doSomething();    iface.somethingElse("bonobo");}public static void main(String[] args) {consumer(new RealObject());consumer(new SimpleProxy(new RealObject()));//動態代理}}


我就這麼說了,可能是我的理解還不夠深,我覺得動態代理就是類的組合的使用,用一個類裡面使用了另外一個類作為私人變數,實現各種功能,同時還可以執行代理的那個類的各種功能,可以各種攔截,可以判定到底要不要執行這個成員類的方法,或者是執行那個


輸出:

doSomething  obj1
somthingElse bonobo  obj1
SimpleProxy doSomething  obj1
doSomething  obj1
SimpleProxy somethingElse bonobo  obj1
somthingElse bonobo  obj1









聯繫我們

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