转载自https://zhidao.baidu.com/question/572699725.html
普通函数与回调函数主要是在调用方式上有区别:
1、对普通函数的调用:调用程序发出对普通函数的调用后,程序执行立即转向被调用函数执行,直到被调用函数执行完毕后,再返回调用程序继续执行。从发出调用的程序的角度看,这个过程为“调用-->等待被调用函数执行完毕-->继续执行”。
2、对回调函数调用:调用程序发出对回调函数的调用后,不等函数执行完毕,立即返回并继续执行。这样,调用程序执和被调用函数同时在执行。当被调函数执行完毕后,被调函数会反过来调用某个事先指定函数,以通知调用程序:函数调用结束。这个过程称为回调(Callback),这正是回调函数名称的由来。
转载自https://cloud.tencent.com/developer/article/1359688
什么是回调函数,上面的问题说的是不是很空洞,不是太形象,下面是知乎上的一位网友给的答案:

为了有更直观的体会,下面通过代码来实现上述过程,
/**
* @author LiosWong
* @description 工具接口
* @date 2018/6/23 上午1:03
*/
public interface Tools {
/**
* 打电话
* @param msg
* @return
*/
String getCallMsg(String msg);
}
/**
* @author LiosWong
* @description 顾客类
* @date 2018/6/23 上午1:01
*/
public class Customer implements Tools{
@Override
public String getCallMsg(String msg) {
if(StringUtils.isNotEmpty(msg)){
System.out.println(msg);
return "已收到电话,马上来取货";
}
return "";
}
public static void main(String[] args) {
Customer customer = new Customer();
SalesPerson salesPerson = new SalesPerson();
salesPerson.callCustomer("ok",customer);//售货员通知用户有货了。
}
}
/**
* @author LiosWong
* @description 售货员
* @date 2018/6/23 上午1:01
*/
public class SalesPerson {
public void callCustomer(String msg,Tools tools){
if("ok".equals(msg)){
String response = tools.getMsg("已经到货啦,请前来购买~");
System.out.println(response);
}
}
}
首先新建一个抽象工具类,里面具体使用电话工具作为通讯方法(回调函数),然后顾客要有电话,所以实现了这个接口;
售货员需要在有货时通知顾客,所以需要有个通知顾客的方法callCustomer,入参数中有Tools接口的引用(登记回调函数),然后在该方法中调用Tools的方法,通知顾客已经有货了(调用回调函数),顾客接受到电话通知(回调响应);
然后在Customer类的main方法中, callCustomer方法的入参,传入了Customer的实例.
博客介绍了普通函数与回调函数在调用方式上的区别。普通函数调用后需等待其执行完毕再继续,而回调函数调用后不等执行完毕,调用程序就继续执行,被调函数执行完会回调指定函数通知。还通过代码示例,以售货员通知顾客有货为例进行说明。
774

被折叠的 条评论
为什么被折叠?



