if/else问题解决(一)函数式编程

过去的,未来的
2020-03-24 / 0 评论 / 0 点赞 / 1,314 阅读 / 0 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2020-04-04,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

一、案例

  public static Integer add(Integer a1, Integer b1, Integer c1) {
        return a1 + b1 + c1;
  }

    public static Integer sub(Integer a1, Integer b1, Integer c1{
        return a1 - b1 - c1;
    }

    public static void test(Integer a1, Integer b1, Integer c1) {
        String type = "add";
        if ("add".equals(type)) {
            add(a1, b1, c1);
        } else if ("sub".equals(type)) {
            sub(a1, b1, c1);
        }		
//这里可能还有很多情况
    }

之前我们写这种在逻辑很多的时候要写很多if/esle,代码深度很深。代码中如果if-else比较多,阅读起来比较困难,维护起来也比较困难,很容易出bug。

二、采用函数式编程解决if/else的问题

1、首先我们定义自己的funtion接口
public interface MyFunction<T, T1, T2, R> {

    R apply(T t, T1 t1, T2 t2);
}
2、编写处理代码
  public static void main(String[] args) {
        Map<String, MyFunction> actionMapps = new HashMap<>();
        MyFunction<Integer, Integer, Integer, Integer> addf = (a, b, c) -> add(a, b, c);
        MyFunction<Integer, Integer, Integer, Integer> subf = (a, b, c) -> sub(a, b, c);
        actionMapps.put("add", addf);
        actionMapps.put("sub", subf);
        System.out.println(actionMapps.get("sub").apply(10, 5, 3));

    }

这样就实现了,采用函数式编程模式解决多if/else的问题。

0

评论区