#异步处理技术之回调的实现
- 回调函数主要分为四个模块:
- 主函数:整个程序的执行引擎,用于按顺序执行各项函数。
- 起始函数:中间函数的调用者,可以直接由主函数作为起始函数。
- 中间函数:介于主函数和回调函数之间,把回调函数传入到中间函数中的动作称之为登记回调函数,当事件被触发时,通知主函数执行回调函数,中间函数则作为一个桥梁的存在。
- 回调函数:独立运行的函数,执行某一项具体的功能。
- 回调函数的形式:
- 同步回调:把函数b传递给函数a。执行a的时候,回调了b,a要一直等到b执行完才能继续执行;
- 异步回调:把函数b传递给函数a。执行a的时候,回调了b,然后a就继续往后执行,b独自执行。
- 同步回调具体代码的实现:
/**
* 工人类
*/
public class Worker {
/**
* 起始函数
* 开始工作
*/
public void doWork() {
Fetcher fetcher = new MyFetcher(new Data(54352, 51542));
fetcher.fetchData(new FetcherCallback() {
@Override
public void success(Data data) {
System.out.println("运算结果:" + data.add());
}
@Override
public Throwable error() {
return new Throwable("数学运算异常");
}
});
}
/**
* 主函数
*
* @param args 系统(命令行)参数
*/
public static void main(String[] args) {
Worker worker = new Worker();
worker.doWork();
}
}
/**
* 数据捕获类
*/
public interface Fetcher {
/**
* 中间函数
*/
void fetchData(FetcherCallback callback);
}
/**
* 中间函数的具体表现形式
*/
public class MyFetcher implements Fetcher {
private Data data;
public MyFetcher(Data data) {
this.data = data;
}
@Override
public void fetchData(FetcherCallback callback) {
try {
System.out.println("回调函数被执行");
callback.success(data);
System.out.println("继续执行当前函数");
} catch (Exception e) {
throw new RuntimeException(callback.error());
}
}
}
/**
* 回调类
*/
public interface FetcherCallback {
/**
* 回调函数=》数据校验成功
*/
void success(Data data);
/**
* 回调函数=》数据校验失败
*/
Throwable error();
}
/**
* 数据运算类
*/
public class Data {
private int x;
private int y;
public Data(int x, int y) {
this.x = x;
this.y = y;
}
public int add() {
return this.x + this.y;
}
public int add(int x, int y) {
return x + y;
}
}
回调函数被执行
运算结果:105894
继续执行当前函数