標籤:java編程思想 callback interface
/*** 書本:《Thinking In Java》* 功能:關於java中的閉包與回調,這裡回調區別於C++,C++中回調的話寄託於指標* 檔案:Callbacks.java* 時間:2015年4月3日20:26:43* 作者:cutter_point*/package Lession10innerclasses;import static net.mindview.util.Print.*;//建立一個介面,包含一個函數interface Incrementable{void increment();}//介面中沒有上面特別的地方,實現這個介面很簡單,直接覆蓋方法就可以了class Callee1 implements Incrementable{private int i = 0;@Overridepublic void increment() {++i;print(i);}}//然後我們要有一個類,裡面有一個和上面介面一樣的方法,只是具體實現的方式不一樣class MyIncrement{public void increment() { print("Other operation"); }static void f(MyIncrement mi) { mi.increment(); }}//如果我們必須繼承上面的MyIncrement的話,那麼上面那個裡面已經有了具體的方法實現了,如果我們把它覆蓋的話,那麼上面的那個的功能就不能用了class Callee2 extends MyIncrement{private int i = 0;public void increment(){super.increment();//實現父類的這個方法,然後再是自己的方法++i;print(i);}//如果自己也想有一個對應的increment方法的話,那麼就用內部類實現private class Closure implements Incrementable{void test() {}@Overridepublic void increment() {Callee2.this.increment(); //這個調用的是Callee2,也就是外部類的方法}}Incrementable getCallbackReference(){return new Closure();}}//為了調用increment函數,我們建立一個對象,專門調用函數的調用者class Caller{private Incrementable callbackReference;Caller(Incrementable cbh) { callbackReference = cbh; }void go() { callbackReference.increment(); }}public class Callbacks {public static void main(String [] args){Callee1 c1 = new Callee1();Callee2 c2 = new Callee2();MyIncrement.f(c2);System.out.println("------------------------");Caller caller1 = new Caller(c1);Caller caller2 = new Caller(c2.getCallbackReference());caller1.go();caller1.go();//第二次調用的時候變成了2System.out.println("------------------------");caller2.go(); //還是回到了c2的increment()調用了,因為在c2.getCallbackReference()裡面又回來調用了外部類,也就是c2的內部類的外部類,就是c2caller2.go();}}
輸出:
Other operation obj1
1 obj1
------------------------
1 obj1
2 obj1
------------------------
Other operation obj1
2 obj1
Other operation obj1
3 obj1
裡面caller2.go()的注釋我都覺得莫名其妙,真TM繞口,哎,java編程思想裡面感覺好多這種繞來繞去的代碼= =,我又不敢說不實用,不然我覺得絕壁有一群人出來噴我。。。
【ThinkingInJava】18、 關於java中的閉包與回調