回调函数实际上就是在调用某个函数时,将自己的一个函数(这个函数为回调函数)的地址(在JAVA中称为引用)作为参数传递给那个函数。而那个函数在需要的时候,利用传递的地址调用回调函数中的函数或成员等。Thimking in Java 第二版中文279--280页的那个程序解释得很清楚。
interface Incrementable {
void increment();
}// Very simple to just implement the interface:
class Callee1 implements Incrementable {
private int i = 0;
public void increment() {
i++;
System.out.println(i);
}
}class MyIncrement {
public void increment() {
System.out.println("Other operation");
}
public static void f(MyIncrement mi) {
mi.increment();
}
}// If your class must implement increment() in
// some other way, you must use an inner class:
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 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);
Caller caller1 = new Caller(c1);
Caller caller2 =
new Caller(c2.getCallbackReference());
caller1.go();
caller1.go();
caller2.go();
caller2.go();
}
} ///:~
在这个函数中Closure就是所谓的回调函数,Caller的构造函数可接收Closuer类型,而正如本例中的Caller caller2 =
new Caller(c2.getCallbackReference());
caller2.go();
就是常用的调用回调函数的手法,caller2实质上调用的是Closuer的increment()方法!
在JAVA中,一般在事件处理中会经常用到回调函数!
interface Incrementable {
void increment();
}// Very simple to just implement the interface:
class Callee1 implements Incrementable {
private int i = 0;
public void increment() {
i++;
System.out.println(i);
}
}class MyIncrement {
public void increment() {
System.out.println("Other operation");
}
public static void f(MyIncrement mi) {
mi.increment();
}
}// If your class must implement increment() in
// some other way, you must use an inner class:
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 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);
Caller caller1 = new Caller(c1);
Caller caller2 =
new Caller(c2.getCallbackReference());
caller1.go();
caller1.go();
caller2.go();
caller2.go();
}
} ///:~
在这个函数中Closure就是所谓的回调函数,Caller的构造函数可接收Closuer类型,而正如本例中的Caller caller2 =
new Caller(c2.getCallbackReference());
caller2.go();
就是常用的调用回调函数的手法,caller2实质上调用的是Closuer的increment()方法!
在JAVA中,一般在事件处理中会经常用到回调函数!
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货