闭包(Closure)是一种能被调用的对象,它保存了创建它的作用域的信息
public class Programmer {
private String name; public Programmer() {
super();
} public Programmer(String name) {
super();
this.name = name;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public void work() {
System.out.println(name + "正在编程");
}
}
public interface Teachable {
public void work();
}
public class TeachableProgrammer extends Programmer { public TeachableProgrammer() {
super();
} public TeachableProgrammer(String name) {
super(name);
} // 教学工作任然由TeachableProgrammer定义
private void teach(String content) {
System.out.println(getName() + "正在教授"+content);
} private class Closure implements Teachable {
String content = ""; Closure (String content){
this.content = content;
}
@Override
public void work() {
// 非静态内部类实现Teachable的work方法,作用仅仅是向客户类提供一个回调外部类的途径
teach(content);
}
} // 返回一个非静态内部类的引用,允许外部类通过该引用来回调外部类的方法
public Teachable getCallbackReference(String content) {
return new Closure(content);
}
}
public class TestClosure { public static void main(String[] args) {
TeachableProgrammer tp = new TeachableProgrammer("李刚");// 该示例来源于李刚老师的疯狂讲义
// 直接调用TeachableProgrammer从Programmer类继承下来的work方法
tp.work();
// 表明上看是调用的Closure的work方法,实际上是通过通过work方法回调TeachableProgrammer的teach方法
tp.getCallbackReference("数学").work(); } }