使用接口 (摘自网络,总结的不错)
也就是使用多态来实现回调函数
public interface ICallback {
public void func();
}
public class ClassWithCallbackFunction implements ICallback{
public ClassWithCallbackFunction() {
}
public void func(){
System.out.println("cccccccccccccccccc");
}
}
public class Caller {
ICallback callback;
public void doCallback() {
callback.func();
}
public void setCallback(ICallback callback) {
this.callback = callback;
}
}
public class MainClass {
public MainClass() {
}
public static void main(String[] args) {
Caller caller = new Caller();
caller.setCallback(new ClassWithCallbackFunction() {
public void func() {
System.out.println("aaaaaaaaaa");
}
});
caller.doCallback();
}
}
现实中是把doCallback()方法放在setCallback里调用,以上是为了说明回调原理
public class Caller {
ICallback callback;
public void doCallback() {
callback.func();
}
public void setCallback(ICallback callback) {
this.callback = callback;
doCallback();
}
} |
|