Java使用Function包&策略模式,优化业务代码大量if...else语句

目录

场景模拟

Consumer与ToIntBiFunction简介,u>

 场景Demo业务代码改造

最终结果


业务代码中,若存在大量无法避免的if...else代码,可以尝试使用JDK8提供的函数式编程包。


场景模拟

设计一个简单的招聘业务:

招聘条件是:男18~60岁,女18~50岁。再根据男女不同年龄段,分配不同的事情任务做。

模拟代码如下

package cn.daydayup.designmode.factorymode.demov4;


/**
 * @author ShangHai
 * @desc
 */
public class Demo {

    /**
     * 模拟招聘业务
     * @param sex 性别
     * @param age 年龄
     * @param name 名字
     */
    public void recruit(String sex, int age, String name){
        if(CommonConstants.MAN.equals(sex)){
            // 男性
            if(age > CommonConstants.SIXTY){
                throw new RuntimeException("年龄不满足");
            } else if(age > CommonConstants.FORTY_FIVE){
                this.doSomeThings001(name);
            } else if(age >= CommonConstants.THIRTY){
                this.doSomeThings002(name);
            } else if(age >= CommonConstants.EIGHTEEN){
                this.doSomeThings003(name);
            } else {
                throw new RuntimeException("年龄不满足");
            }
        } else if(CommonConstants.WOMAN.equals(sex)) {
            // 女性
            if(age > CommonConstants.FIFTY){
                throw new RuntimeException("年龄不满足");
            } else if(age >= CommonConstants.THIRTY){
                this.doSomeThings004(name);
            } else if(age >= CommonConstants.EIGHTEEN){
                this.doSomeThings005(name);
            } else {
                throw new RuntimeException("年龄不满足");
            }
        } else {
            throw new RuntimeException("性别不满足");
        }
    }

    private void doSomeThings001(String name){
        System.out.println(name + "[男]年龄45-60");
    }

    private void doSomeThings002(String name){
        System.out.println(name + "[男]年龄30-45");
    }

    private void doSomeThings003(String name){
        System.out.println(name + "[男]年龄18-30");
    }

    private void doSomeThings004(String name){
        System.out.println(name + "[女]年龄30-60");
    }

    private void doSomeThings005(String name){
        System.out.println(name + "[女]年龄18-30");
    }

}

常量代码 

package cn.daydayup.designmode.factorymode.demov4;

/**
 * @author ShangHai
 * @desc
 */
public class CommonConstants {

    public final static int ZERO = 0;

    public final static int ONE = 1;

    public final static int TWO = 2;

    public final static int THRRE = 3;

    public final static int FOUR = 4;

    public final static int FIVE = 5;

    public final static int EIGHTEEN = 18;

    public final static int THIRTY = 30;

    public final static int FORTY_FIVE = 45;

    public final static int FIFTY = 50;

    public final static int SIXTY = 60;

    public final static String MAN = "男";

    public final static String WOMAN = "女";

}

 main方法执行【控制台:GeGeDa[男]年龄45-60

public static void main(String[] args) {
        // 控制台输出:​ 【GeGeDa[男]年龄45-60】
        new Demo().recruit(CommonConstants.MAN, 49, "GeGeDa");
    }

上述的业务方法中,存在较多的if...else条件语句。

若条件维度根据业务需求增多,if...else语句将会不断叠加,业务代码将变得不再优雅。

分析以上业务代码,可采用Function包中的Consumer<T>与ToIntBiFunction<T,U>配合进行改造。


Consumer<T>与ToIntBiFunction<T,U>简介

Consumer<T>

Consumer<T>接口是java.util.function包的其中一个接口,

包含一个核心方法accept(T t),其意义即传入一个参数进行消费,无返回值。


代码测试如下:

package cn.daydayup.designmode.factorymode.demov4.test;

import java.util.function.Consumer;

/**
 * @author ShangHai
 * @desc
 */
public class TestConsumer {

    public static void main(String[] args) {
        Consumer<String> consumer = a -> {
            System.out.println("输出参数值:" + a);
        };

        // 传入字符串参数
        consumer.accept("aaaa");
    }

}

以上consumer对象声明的方式,等同于

Consumer<String> consumer = new Consumer<String>() {
            @Override
            public void accept(String a) {
                System.out.println("输出参数值:" + a);
            }
        };

main方法执行【控制台:输出参数值:aaaa

 ToIntBiFunction<T,U>

ToIntBiFunction<T,U>接口是java.util.function包的其中一个接口,

包含一个核心方法applyAsInt(T t,U u),其意义即传入两个参数进行消费,返回一个int值。


代码测试如下:

package cn.daydayup.designmode.factorymode.demov4.test;

import cn.daydayup.designmode.CommonConstant;
import cn.daydayup.designmode.factorymode.demov4.CommonConstants;

import java.util.function.ToIntBiFunction;

/**
 * @author ShangHai
 * @desc
 */
public class TestToIntBiFunction {

    public static void main(String[] args) {
        // 传入两个String参数,得到一个int值
        ToIntBiFunction<String, String> toIntBiFunction = (a, b) -> {
            if(a.equals(b)){
                return CommonConstants.ONE;
            } else {
                return CommonConstants.TWO;
            }
        };

        // 传入两个字符串参数
        int result = toIntBiFunction.applyAsInt("参数1", "参数2");
        System.out.println("得到的int值" + result);
    }

}

以上toIntBiFunction对象声明的方式,等同于

ToIntBiFunction<String, String> toIntBiFunction = new ToIntBiFunction<String, String>() {
            @Override
            public int applyAsInt(String a, String b) {
                if(a.equals(b)){
                    return CommonConstants.ONE;
                } else {
                    return CommonConstants.TWO;
                }
            }
        };

main方法执行【控制台:得到的int值2


 场景Demo业务代码改造

一、if条件&逻辑代码抽离

创建一个策略列表业务执行类RecruitConsumer,

用来存储if标签体内实际的执行方法。

package cn.daydayup.designmode.factorymode.demov4.function;

import cn.daydayup.designmode.factorymode.demov4.CommonConstants;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

/**
 * @author ShangHai
 * @desc
 */
public class RecruitConsumer {

    // 策略列表
    public static final Map<Integer, Consumer<String>> CONSUMER_MAP = new HashMap<>();

    static {
        // 根据传入不同的int值,将执行不同方法
        CONSUMER_MAP.put(CommonConstants.ONE, RecruitConsumer::doSomeThings001);
        CONSUMER_MAP.put(CommonConstants.TWO, RecruitConsumer::doSomeThings002);
        CONSUMER_MAP.put(CommonConstants.THRRE, RecruitConsumer::doSomeThings003);
        CONSUMER_MAP.put(CommonConstants.FOUR, RecruitConsumer::doSomeThings004);
        CONSUMER_MAP.put(CommonConstants.FIVE, RecruitConsumer::doSomeThings005);
    }

    private static void doSomeThings001(String name){
        System.out.println(name + "[男]年龄45-60");
    }

    private static void doSomeThings002(String name){
        System.out.println(name + "[男]年龄30-45");
    }

    private static void doSomeThings003(String name){
        System.out.println(name + "[男]年龄18-30");
    }

    private static void doSomeThings004(String name){
        System.out.println(name + "[女]年龄30-60");
    }

    private static void doSomeThings005(String name){
        System.out.println(name + "[女]年龄18-30");
    }

}

创建一个"条件收集&策略数值"返回类RecruitToIntBiFunction,

用来收集需求下所有的if分支,且根据if满足的条件返回一个策略列表需要的策略int数值。

package cn.daydayup.designmode.factorymode.demov4.function;

import cn.daydayup.designmode.CommonConstant;
import cn.daydayup.designmode.factorymode.demov4.CommonConstants;

import java.util.function.ToIntBiFunction;

/**
 * @author ShangHai
 * @desc
 */
public class RecruitToIntBiFunction implements ToIntBiFunction{

    @Override
    public int applyAsInt(Object o, Object o2) {
        if(o==null || o2==null){
            // 返回0,RecruitConsumer策略列表不具备0策略,不执行任何逻辑
            return CommonConstants.ZERO;
        }

        String sex = o.toString();
        int age = Integer.parseInt(o2.toString());
        if(CommonConstants.MAN.equals(sex)){
            // 男性
            if(age > CommonConstants.SIXTY){
                // 返回0,RecruitConsumer策略列表不具备0策略,不执行任何逻辑
                return CommonConstants.ZERO;
            } else if(age > CommonConstants.FORTY_FIVE){
                return CommonConstants.ONE;
            } else if(age >= CommonConstants.THIRTY){
                return CommonConstants.TWO;
            } else if(age >= CommonConstants.EIGHTEEN){
                return CommonConstants.THRRE;
            } else {
                // 返回0,RecruitConsumer策略列表不具备0策略,不执行任何逻辑
                return CommonConstants.ZERO;
            }
        } else if(CommonConstants.WOMAN.equals(sex)) {
            // 女性
            if(age > CommonConstants.FIFTY){
                // 返回0,RecruitConsumer策略列表不具备0策略,不执行任何逻辑
                return CommonConstants.ZERO;
            } else if(age >= CommonConstants.THIRTY){
                return CommonConstants.FOUR;
            } else if(age >= CommonConstants.EIGHTEEN){
                return CommonConstants.FIVE;
            } else {
                // 返回0,RecruitConsumer策略列表不具备0策略,不执行任何逻辑
                return CommonConstants.ZERO;
            }
        } else {
            // 返回0,RecruitConsumer策略列表不具备0策略,不执行任何逻辑
            return CommonConstants.ZERO;
        }
    }

}

二、业务逻辑代码改造(最终仅需两行)

package cn.daydayup.designmode.factorymode.demov4;


import cn.daydayup.designmode.factorymode.demov4.function.RecruitConsumer;
import cn.daydayup.designmode.factorymode.demov4.function.RecruitToIntBiFunction;

/**
 * @author ShangHai
 * @desc
 */
public class Demo {

    /**
     * 模拟招聘业务
     * @param sex 性别
     * @param age 年龄
     * @param name 名字
     */
    public void recruit(String sex, int age, String name){
        // 将if条件所需参数传入,得到策略int数值
        int strategyInt = new RecruitToIntBiFunction().applyAsInt(sex, age);
        // 将策略int数值传入策略列表,consumer会自动执行对应的策略方法
        RecruitConsumer.CONSUMER_MAP.get(strategyInt).accept(name);
    }

    public static void main(String[] args) {
        // 控制台输出 ShangHai[男]年龄18-30
        new Demo().recruit(CommonConstants.MAN, 18, "ShangHai");
    }
}




 main方法执行【控制台:ShangHai[男]年龄18-30


最终结果

业务方法经过"Funtion包与策略模式"改造后,

代码变得简洁;

业务方法不再关注if如何实现,交由定义好的策略消费即可;

if...else分支语句及业务实际执行方法分类被收集,代码整体层次变得规范。

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个简单的 Java代码生成工具的示例: 1. 定义输入和输出: ``` // 输入:Java 代码字符串 String javaCode; // 输出:伪代码字符串 String pseudocode; ``` 2. 解析输入的 Java 代码: ``` // 使用 JavaParser 库解析 Java 代码 CompilationUnit cu = JavaParser.parse(javaCode); ``` 3. 遍历解析后的 AST(抽象语法树),将 Java 代码转换为伪代码: ``` // 遍历 AST,将每个节点转换为伪代码 for (Node node : cu.getChildNodes()) { pseudocode += convertNodeToPseudocode(node); } ``` 4. 实现 convertNodeToPseudocode 方法,将每个节点转换为伪代码: ``` private String convertNodeToPseudocode(Node node) { // 判断节点类型,根据节点类型转换为伪代码 if (node instanceof MethodDeclaration) { MethodDeclaration methodDeclaration = (MethodDeclaration) node; String methodName = methodDeclaration.getNameAsString(); String methodReturnType = methodDeclaration.getTypeAsString(); List<Parameter> methodParameters = methodDeclaration.getParameters(); String pseudocode = "Function " + methodName + "("; for (Parameter parameter : methodParameters) { String parameterName = parameter.getNameAsString(); String parameterType = parameter.getTypeAsString(); pseudocode += parameterType + " " + parameterName + ", "; } if (!methodParameters.isEmpty()) { pseudocode = pseudocode.substring(0, pseudocode.length() - 2); } pseudocode += ") -> " + methodReturnType + " {\n"; pseudocode += // 调用 convertNodeToPseudocode 方法,将方法体转换为伪代码 pseudocode += "}\n"; return pseudocode; } else if (node instanceof IfStmt) { IfStmt ifStmt = (IfStmt) node; String pseudocode = "If (" + ifStmt.getCondition() + ") {\n"; pseudocode += // 调用 convertNodeToPseudocode 方法,将 if 语句块转换为伪代码 pseudocode += "}\n"; return pseudocode; } else if (...) { // 根据需要实现其他节点类型的转换 } } ``` 5. 最终得到转换后的伪代码: ``` Function add(int a, int b) -> int { return a + b; } If (x > 0) { y = x * 2; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值