紅知博客

          知其然,亦知其所以然
          posts - 32, comments - 35, trackbacks - 0, articles - 0

          java中的閉包與回調 (轉)

          Posted on 2007-09-17 14:44 紅子 閱讀(1256) 評論(1)  編輯  收藏 所屬分類: JAVAJ2EE 綜合

          java中的閉包與回調


          閉包是一個可調用的對象,它記錄了一些信息,這些信息來自于創建他的作用域,用過這個定義 可以看出內部類是面向對象的閉包 因為他不僅包含外圍類對象的信息 還自動擁有一個指向此外圍類對象的引用 在此作用域內 內部類有權操作所有的成員 包括private成員;

          interface Incrementable
          {
           void increment();
          }

           

          class Callee1 implements Incrementable
          {
           private int i=0;
           public void increment()
           {
            i++;
            System.out.println(i);
           }
          }

          class MyIncrement
          {
           void increment()
           {
            System.out.println("other increment");
           }
           static void f(MyIncrement mi)
           {
            mi.increment();
           }
          }

          class Callee2 extends MyIncrement
          {
           private int i=0;
           private void incr()
           {
            i++;
            System.out.println(i);
           }
           private class Closure implements Incrementable
           {
            public void increment()
            {
             incr();
            }
           }
           Incrementable getCallbackReference()
           {
            return new Closure();
           }
          }

          class Caller
           {
            private Incrementable callbackRefference;
            Caller(Incrementable cbh)
            {
             callbackRefference = cbh;
            }
            void go()
            {
             callbackRefference.increment();
            }
           }

          public class Callbacks
          {
           public  static void main(String [] args)
           {
            Callee1 c1=new Callee1();
            Callee2 c2=new Callee2();
            MyIncrement.f(c2);
            Caller caller1 =new  Caller(c1);
            Caller caller2=new Caller(c2.getCallbackReference());
            caller1.go();
            caller1.go();
            caller2.go();
            caller2.go();
           }
          }

          輸出

          other increment
          1
          2
          1
          2

          Callee2 繼承字MyIncrement 后者已經有一個不同的increment()方法 并且與Incrementable接口期望的increment()方法完全不相關 所以如果Callee2繼承了MyIncrement 就不能為了Incrementable的用途而覆蓋increment()方法 于是這能使用內部類獨立的實現Incrementable

          內部類Closure實現了Incrementable 一提供一個放回Caller2的鉤子 而且是一個安全的鉤子 無論誰獲得此Incrementbale的引用 都只能調用increment() 除此之外沒有其他功能

          Feedback

          # re: java中的閉包與回調 (轉)  回復  更多評論   

          2007-09-28 15:32 by 千里冰封
          現在還沒有實現閉包吧
          我要啦免费统计
          主站蜘蛛池模板: 西宁市| 林口县| 华亭县| 淮安市| 太仓市| 临泽县| 修武县| 吉木乃县| 石嘴山市| 杭州市| 花垣县| 平乐县| 渭源县| 涞水县| 西华县| 金溪县| 嘉祥县| 兰考县| 永城市| 本溪市| 虹口区| 女性| 云南省| 泸水县| 望城县| 寿宁县| 澜沧| 什邡市| 大洼县| 韩城市| 康平县| 达日县| 乐清市| 昌乐县| 沿河| 太仓市| 襄城县| 茂名市| 江北区| 石嘴山市| 怀来县|