回调函数

时间:2022-06-13
本文章向大家介绍回调函数,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应 --摘自百度百科--

什么是回调函数,上面的问题说的是不是很空洞,不是太形象,下面是知乎上的一位网友给的答案:

为了有更直观的体会,下面通过代码来实现上述过程,

/**
 * @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的实例.