Java 8 函数式替换if else动态执行实现代码

Java 8 函数式替换if else动态执行代码

使用场景

  • 过多的if else结构判断语句 , 优化代码结构,扁平化编写代码,代码更好维护

  • 需要动态执行逻辑代码,把实现代码参数化传递执行

Demo

  • 编写函数式接口
/**
 * 执行代码的函数式接口
 * @author earl
 * @date 2020-07-06
 */
@FunctionalInterface
public interface ExecFunction {

     void exec( );

}
/** 
 * 执行代码的并返回结果的函数式接口
 * @author earl
 * @date 2020-07-15
 */
@FunctionalInterface
public interface ExecReturnFunction <T> {

     T exec( );

}
  • 支持函数式批量调用的BO(Business Object),一般情况下不需要
/**
 * 支持批量函数操作的 BO
 * @author earl
 * @date 2020-07-09
 */
@Data
@Accessors(chain = true)
@NoArgsConstructor
public class FuncBO <T>  {

     public FuncBO(Boolean right, ExecFunction func) {
          this.right = right;
          this.func = func;
     }

     public FuncBO(Boolean right, ExecReturnFunction <T> returnFunc) {
          this.right = right;
          this.returnFunc = returnFunc;
     }

     private Boolean right;

     private ExecFunction func;

     private ExecReturnFunction <T>  returnFunc;
}
  • 编写工具类封装调用
 

import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;

/**
 *  函数工具
 * @author earl
 * @date 2020-07-02
 */
public final class  FunctionUtil  {

    private  FunctionUtil(){}

    /**
     * 函数式接口执行代码
     * @param match  条件匹配,若匹配执行ExecFunction代码
     * @param function  执行的函数式代码
     */
    public static void matchExec(boolean match, ExecFunction function) {
        if (!match) {
            return  ;
        }
        function.exec();
    }

    /**
     * 函数式接口执行代码
     * @param match  条件匹配,若匹配执行ExecReturnFunction代码
     * @param function  执行的函数式代码
     * @return 返回结果
     */
    public static <T> T matchExecReturn(boolean match, ExecReturnFunction <T> function) {
        if (!match) {
            return null;
        }
        return function.exec();
    }




    /**
     * 批量执行函数代码
     * 不确保线程安全(具体看使用场景)
     * @param functions  函数数组
     */
    public static void batchExec(List<FuncBO> functions) {
        functions.stream().filter(data -> Objects.equals(true, data.getRight())).forEach(data->data.getFunc().exec());
    }


    /**
     * 函数式接口执行代码 ( Predicate利用支持泛型方式 )
     * @param predicate  Predicate接口函数
     * @param obj     Predicate 对应的泛型对象
     * @param function  执行的函数式代码
     */
    public static <T> void  matchExec(Predicate <T> predicate,T obj, ExecFunction function) {
        if (!predicate.test(obj)) {
            return  ;
        }
        function.exec();
    }



}

测试

  • 代码优化之前
   public static void main(String [] args){
        List<Integer> list = new ArrayList<>(1);
        list.add(0);
        if (list.size() == 1) {
            list.add(2); 
        }
   }
  • 代码优化之后
   public static void main(String [] args){
        List<Integer> list = new ArrayList<>(1);
        list.add(0);
        matchExec(list.size() == 1,()-> list.add(2));
   }
  • 代码优化之前
   public static void main(String [] args){
        int i = 4;
        if ( Objects.equals(i,1) ) {
            System.out.println("调用A接口");
        }else if ( Objects.equals(i,2) ) {
            System.out.println("调用B接口");
        }else if ( Objects.equals(i,3) ) {
            System.out.println("调用C接口");
        }else if ( Objects.equals(i,4) ) {
            System.out.println("保存至数据A表");
        }else if ( Objects.equals(i,5) ) {
            System.out.println("保存至数据B表");
        }
    }
  • 代码优化之后
    public static void main(String [] args){
        int i = 4;
        Map<Integer, ExecFunction> mapFunc = new HashMap<>();
        mapFunc.put(1, () -> System.out.println("调用A接口"));
        mapFunc.put(2, () -> System.out.println("调用B接口"));
        mapFunc.put(3, () -> System.out.println("调用C接口"));
        mapFunc.put(4, () -> System.out.println("保存至数据A表"));
        mapFunc.put(5, () -> System.out.println("保存至数据B表"));

        mapFunc.forEach((key, value) -> {
            if (Objects.equals(key, i)) {
                value.exec();
            }
        });
    }

你可能感兴趣的:(java,函数式编程,重构代码,java8,优化代码)