Loading

什么是函数回调

什么是函数回调?

介绍

函数回调是一种编程概念,它描述的是这样一个过程:一个函数(称为回调函数)作为参数传递给另一个函数(称为调用函数),当满足一定条件或者在某个特定时刻,调用函数会调用传递过来的回调函数。这种机制允许程序员在编写代码时,能够在不同的上下文中重用函数,同时也能实现异步处理、事件驱动编程以及模块间的松散耦合

示例

以Java为例,由于Java语言不直接支持函数指针,因此通常通过接口实现回调机制,比如函数式接口Function

// 这是一个回调接口
public interface Function<T, R> {

    /**
     * 
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);
    
}

public class TestFunctionCallBack {

    @Test
    public void mainMethod(){
        String str1 = test(String::toUpperCase,"hello");
        String str2 = test(this::switchCase,"HeLLo");
        log.info("str1:{}", str1);
        log.info("str2:{}", str2);
    }

    /**
     * 这个方法(调用函数)接收 函数作为参数
     * @param function
     * @param args
     * @return
     */
    public static String test(Function<String,String> function,String args){
        //调用回调函数的具体方法
        return "{"+function.apply(args)+"}";
    }

    /**
     * 大写转小写,小写转大写
     *
     * @param source 来源
     * @return {@link String}
     */
    public String switchCase(String source){
        char[] charArray = source.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            char c = charArray[i];
            if (c >= 'a' && c <= 'z') {
                c = (char) (c - 32);
            }else if (c >= 'A' && c <= 'Z') {
                c = (char) (c + 32);
            }
            charArray[i] = c;
        }
        return new String(charArray);
    }

}

上述代码中test方法中的参数为一个函数(函数式接口),从本例来看解耦了test和字符串的具体处理逻辑,对于不同的字符串实现只需要传入不同的函数即可,而不需要去修改test中的代码,实现了在不同的上下文中重用函数

posted @ 2024-03-08 10:34  VoidCm  阅读(43)  评论(0编辑  收藏  举报