分析Java中的閉包與回調(diào)方法
關(guān)于閉包,我們之前介紹過相關(guān)的一些文章,比如:《Javascript閉包(closure) 深入淺出》、《C#中的閉包是怎么捕獲變量的》和《深入理解Perl閉包及其應(yīng)用》,大家可以對比著看一下,供參考。
閉包是一個可調(diào)用的對象,它記錄了一些信息,這些信息來自于創(chuàng)建他的作用域,用過這個定義 可以看出內(nèi)部類是面向?qū)ο蟮拈]包 因為他不僅包含外圍類對象的信息 還自動擁有一個指向此外圍類對象的引用 在此作用域內(nèi) 內(nèi)部類有權(quán)操作所有的成員 包括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 //內(nèi)部類
- {
- public void increment()
- {
- incr();
- }
- }
- Incrementable getCallbackReference()
- {
- return new Closure(); //新建內(nèi)部類
- }
- }
- class Caller
- {
- private Incrementable callbackRefference;
- Caller(Incrementable cbh)
- {
- callbackRefference = cbh;
- }
- void go()
- {
- callbackRefference.increment();//調(diào)用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());//將內(nèi)部類中的Closure賦給Caller
- caller1.go();
- caller1.go();
- caller2.go();
- caller2.go();
- }
- }
輸出:
other increment
1
2
1
2
Callee2 繼承字MyIncrement 后者已經(jīng)有一個不同的increment()方法并且與Incrementable接口期望的increment()方法完全不相關(guān) 所以如果Callee2繼承了MyIncrement 就不能為了Incrementable的用途而覆蓋increment()方法 于是這能使用內(nèi)部類獨(dú)立的實現(xiàn)Incrementable
內(nèi)部類Closure實現(xiàn)了Incrementable 一提供一個放回Caller2的鉤子 而且是一個安全的鉤子 無論誰獲得此Incrementbale的引用 都只能調(diào)用increment() 除此之外沒有其他功能。
希望通過本文的介紹,能給你帶來幫助。
【編輯推薦】