当前位置: 代码迷 >> 综合 >> JAVA8 BiFunction接口用于解耦
  详细解决方案

JAVA8 BiFunction接口用于解耦

热度:39   发布时间:2023-12-02 00:52:37.0

先看源码

@FunctionalInterface
public interface BiFunction<T, U, R> {/*** 输入两个参数, 类型分别是T和U, 返回一个结果, 类型为R* @param t 函数第一个输入参数* @param u 第二个输入参数* @return 返回结果*/R apply(T t, U u);/*** 传入一个Function类型,该Function类型输入参数为R, 返回结果类型为V* 当前BiFunction的apply函数输入参数类型为T, U; 返回结果类型为R* 将两个参数组合之后返回一个新的BiFunction方法, 输入参数是T,U,返回结果类型为V* 简单来说就是当前的BiFunction是(T, U) -> R, 传入的Function是R -> V* 所以组合后的新的Function是(T, U) -> V, 即把BiFunction的返回结果作为入参再传入Function中*/default <V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after) {Objects.requireNonNull(after);return (T t, U u) -> after.apply(apply(t, u));}
}

apply()方法例子:

@Slf4j
public class BiFunctionTest {public static void main(String[] args) {test((processId, status) -> {log.info(">>>>>>>main");int result = Integer.parseInt(processId) + status;return result;});}private static void test(BiFunction<String, Integer, Integer> callback) {log.info(">>>>>>>test");Integer apply = callback.apply("1", 2);log.info(">>>>>>>{}", apply);}
}

打印结果:

21:25:34.650 [main] INFO com.ceam.data.tree.common.function.bifunction.BiFunctionTest - >>>>>>>test
21:25:34.652 [main] INFO com.ceam.data.tree.common.function.bifunction.BiFunctionTest - >>>>>>>main
21:25:34.652 [main] INFO com.ceam.data.tree.common.function.bifunction.BiFunctionTest - >>>>>>>3

总结:

    可以把一个大的方法分割为两个,或者把模块分割降低耦合,两者还是存在依赖的。

如果对你有帮助帮忙点个赞哈