轉帖|其它|編輯:郝浩|2010-07-15 12:07:33.000|閱讀 549 次
概述:閉包是一個可調用的對象,它記錄了一些信息,這些信息來自于創建他的作用域,用過這個定義可以看出內部類是面向對象的閉包 因為他不僅包含外圍類對象的信息 還自動擁有一個指向此外圍類對象的引用 在此作用域內內部類有權操作所有的成員 包括private成員,本文主要講述Java中的閉包與回調問題,希望對大家有所幫助。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
閉包是一個可調用的對象,它記錄了一些信息,這些信息來自于創建他的作用域,用過這個定義可以看出內部類是面向對象的閉包 因為他不僅包含外圍類對象的信息 還自動擁有一個指向此外圍類對象的引用 在此作用域內內部類有權操作所有的成員 包括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() 除此之外沒有其他功能。
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自:網絡轉載