一、Closures:A closure is a callable object that retains information from the scope in which it was created.
1》一个可以调用对象,
2》Closures:没有自己任何信息,唯一有一个方法,也是调用包含Closures ,即它建立类的一个方法。
3》Closures权限:只供包含它的类使用。
因此:Inner Class 内部类满足以上所有条件。
理解:就是一个类里面的封闭块,可以得到建立它的类一个连接。哪么可以使用这个类。
也就是:谁建立我,我就拥有谁的功能。
有点像各种代理商,卖衣服,卖瓷砖的代理商
二、callbacks :谁建立我,反过来我可以调用谁
三、 例子:1》项目经理写一个空架子(即接口),里面有一些方法需要实现,并且明确 表示可以有多钟结果。
2》哪么现在有两个编程人员进行具体的功能编写,各写各的,方法一样,结果不一样。
第一:一个类(Callee1 )简单的实现接口
第二:这时,一个编程人员已经写好一个类,而且方法和项目经理写的接口方法还一样,肯定不能简单的实现了,怎么办?
1》 哪么就在类Callee2 封装一个内部私有类(Closures)
2》类里写一个方法直接得到Callee2 的连接。
3》有了连接,就可以使用Callee2 的方法了。
package innerclasses;
import static net.mindview.util.Print.*;
interface Incrementable {
void increment();
}
// Very simple to just implement the interface:
class Callee1 implements Incrementable {
private int i = 0;
public void increment() {
i++;
print(i);
}
}
class MyIncrement {
public void increment() {
print("Other operation");
}
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;
public void increment() {
super.increment();
i++;
print(i);
}
// 得到具体类的连接,并调用具体类的方法 ,这里也叫回调。
private class Closure implements Incrementable {
public void increment() {
// Specify outer-class method, otherwise
// you’d get an infinite recursion:
Callee2.this.increment();
}
}
// 得到具体类下一个封闭类对象
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);
// c2.getCallbackReference() 打印1
Caller caller2 = new Caller(c2.getCallbackReference());
caller1.go();// 出1
caller1.go();// 出2
caller2.go();
caller2.go();
}
}
03-10
462