分析Java中的閉包與回調方法
關于閉包,我們之前介紹過相關的一些文章,比如:《Javascript閉包(closure) 深入淺出》、《C#中的閉包是怎么捕獲變量的》和《深入理解Perl閉包及其應用》,大家可以對比著看一下,供參考。
閉包是一個可調用的對象,它記錄了一些信息,這些信息來自于創建他的作用域,用過這個定義 可以看出內部類是面向對象的閉包 因為他不僅包含外圍類對象的信息 還自動擁有一個指向此外圍類對象的引用 在此作用域內 內部類有權操作所有的成員 包括private成員;
Java代碼
- 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();//調用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());//將內部類中的Closure賦給Caller
- 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() 除此之外沒有其他功能。
希望通過本文的介紹,能給你帶來幫助。
【編輯推薦】