Java编程思想(第四版)
内部类-闭包与回调
闭包(closure)事一个可调用的对象。它纪录了一些信息,这些信息来自于创建它的作用域。通过这个定义,可以看出内部类事面向对象的闭包,因为它不仅包含外围擂对象(创建内部类的作用域)的信息,还自动有用一个指向此外围类对象的引用,在此作用域内,内部类有权操作所有的成员,包括private成员。
下面是自己按照教程实现的一些小Demo。
//Callbacks
/**
* 闭包与回调
*/
public class Callbacks {
public static void main(String[] args) {
Callee1 c1 = new Callee1();
Callee2 c2 = new Callee2();
MyIncrement.f(c1);
Caller callee1 = new Caller(c1);
Caller caller2 = new Caller(c2.getCallbackReference());
callee1.go();
callee1.go();
caller2.go();
caller2.go();
}
}
//callee1.java
package com.test.think.Closure;
public class Callee1 implements Incrementable {
private int i = 0;
@Override
public void increment() {
i++;
System.out.println(i);
}
}
class MyIncrement {
public void increment() {
System.out.println("Other oppration");
}
static void f(Incrementable mi) {
mi.increment();
}
}
class Callee2 extends MyIncrement {
private int i =0;
public void increment() {
super.increment();
i++;
System.out.println(i);
}
private class Closure implements Incrementable {
@Override
public void increment() {
Callee2.this.increment();
}
}
Incrementable getCallbackReference () {
return new Closure();
}
}
class Caller {
private Incrementable callbackReference;
Caller (Incrementable cbn) {
callbackReference = cbn;
}
void go() {
callbackReference.increment();
}
}
//Incrementable.java
public interface Incrementable {
//自增接口
void increment();
}