Java 如何避免代码中大量的 if else 判断

Java 如何避免代码中大量的 if else 判断

在代码中经常会出现 if else 判断,如下图所示:

在这里插入图片描述

两三个还好,但是如果有很多不但影响代码阅读,更会影响代码效率。因此,需要通过一些优化去避免大量的 if else。

解决方案

1.策略模式

策略模式是一种行为型设计模式,它 通过定义一系列算法类(策略类),将算法的实现与使用分离开来,使得算法可以独立于使用它的客户端而变化。在 Java 中,策略模式通常被应用于业务逻辑中,用于处理不同的业务场景和业务规则。

我们可以将各个分支的逻辑封装成不同的策略类,然后通过一个上下文类来根据条件选择合适的策略对象执行相应的逻辑。避免大量的 if else

具体实现如下:

(1) 定义策略类接口或者抽象类,封装具体的算法

/**
 * 策略接口
 */
public interface Strategy {

    // 定义抽象方法
    void doSomething();
}

(2)定义多个具体的策略类,实现该接口或抽象类

实现类 1:

/**
 * 实现类
 */
public class ImplementStrategyA implements Strategy {
    @Override
    public void doSomething() {

//        实现具体算法
        System.out.println("实现具体算法 A");

    }
}

实现类 2:

/**
 * 实现类
 */
public class ImplementStrategyB implements Strategy{
    @Override
    public void doSomething() {

        // 实现具体算法
        System.out.println("实现具体算法 B");
    }
}

(3)定义一个上下文类,用于管理所有的策略

/**
 * 上下文类,用于管理所有的策略
 */
public class Context {

    private Strategy strategy;

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public void doSomethingStrategy() {
        strategy.doSomething();
    }
}

最后,在需要的业务逻辑中,传入相应的策略对象,执行对应的算法:

// 使用示例
if (conditionA) {
    Context context = new Context(new ImplementStrategyA());
    context.doSomethingStrategy();
} else if (conditionB) {
    Context context = new Context(new ImplementStrategyB());
    context.doSomethingStrategy();
}

2.工厂模式

工厂模式是一种 创建型设计模式,它通过定义一个工厂类来封装对象的创建过程,从而将客户端代码与具体的产品实现解耦。在 Java 中,工厂模式通常被应用于对象的创建和组装场景中。具体实现如下:

(1)定义一个 car 接口或抽象类,用于封装 car 的通用接口或抽象父类

public interface Car {

    void doSomething();
}

(2)定义多个具体的 car 类,实现该接口或抽象父类

实现类 1:

public class Audi implements Car{
    @Override
    public void doSomething() {
        
    }
}

实现类 2:

public class BMW implements Car {
    @Override
    public void doSomething() {

    }
}

(3)定义一个工厂类,用于创建产品对象

public class Factory {

    public static Car create(String carName) {

        switch (carName) {
            case "奥迪":
                return new Audi();
            case "宝马":
                return new BMW();
            default:
                throw new IllegalArgumentException("Invalid carName: " + carName);

        }

    }
}

(4)在业务逻辑中,调用工厂类的静态方法,创建对应的产品对象

Car car = Factory.create("宝马");
car.doSomething();

3.策略模式 + 工厂模式

通常我们会把 策略模式 + 工厂模式 进行结合去解决 if else 问题。

案例场景:

如下图所示,不同的 code 编码执行不同的功能。

在这里插入图片描述

(1)条件模块抽象为一个公共的接口,策略接口

public interface Action {

    void doSomeAction();
}

(2)根据每个逻辑,定义出自己具体的策略实现类

public class executeActionOne implements Action{
    @Override
    public void doSomeAction(String code) {
        System.out.println(code);
    }
}


public class executeActionTwo implements Action{
    @Override
    public void doSomeAction(String code) {
        System.out.println(code);
    }
}



public class executeActionThree implements Action{
    @Override
    public void doSomeAction(String code) {
        System.out.println(code);
    }
}

(3)工厂类,统一调度,用来管理这些策略(最重要

import java.util.HashMap;
import java.util.Map;

/**
 * 工厂类
 */
public class ActionFactory {

    //    私有构造方法
    private ActionFactory() {

    }

    //    单例
    private static class SingleHandler {
        private static ActionFactory instance = new ActionFactory();
    }

    //    获得工厂类实例
    public static ActionFactory getInstance() {
        return SingleHandler.instance;
    }

    private static final Map<String, Action> ACTION_MAP = new HashMap<>();

    //    工厂类实例放在 map 中
    static {

        ACTION_MAP.put("1101", new executeActionOne());
        ACTION_MAP.put("1102", new executeActionTwo());
        ACTION_MAP.put("1104", new executeActionThree());

    }

    //    根据不同的编码获得不同的实现类实例
    public static Action getAction(String actionCode) {

        Action action = ACTION_MAP.get(actionCode);

        if (action == null) {
            throw new RuntimeException("无效 actionCode");
        }
        return action;

    }

    //    调用实现类所在方法
    public void doAction(String actionCode) {
        getAction(actionCode).doSomeAction(actionCode);
    }
}

(4)业务逻辑中调用

 ActionFactory.getInstance().doAction("1101");

4.提前 return(适用于分支逻辑很简单的 if else)

if (condition) {

// 业务逻辑;

        } else {
            return;
        }


// 优化后

if (!condition) {

return;

        } 
        
// 业务逻辑;

5.枚举

如下代码:业务中需要大量 if else

		String productStatus;
        if ("1".equals(statusCode)) {
            productStatus = "商品已售出";
        } else if ("2".equals(statusCode)) {
            productStatus = "商品已售罄";
        } else if ("3".equals(statusCode)) {
            productStatus = "商品货存充足";
        } else if ("4".equals(statusCode)) {
            productStatus = "商品需采购";
        }

利用枚举优化,定义枚举:

public enum ProductStatusEnum {


    HAVE_SOLD("1", "商品已售出"),
    SOLD_ALL("2", "商品已售罄"),
    PRODUCT_FULL("3", "商品货存充足"),
    NEED_BUY("4", "商品需采购");

    private String statusCode;

    private String productStatus;

    public String getStatusCode() {
        return statusCode;
    }

    public String getProductStatus() {
        return productStatus;
    }

    // 全参构造
    ProductStatusEnum(String statusCode, String productStatus) {
        this.statusCode = statusCode;
        this.productStatus = productStatus;
    }

    static ProductStatusEnum of(String statusCode) {

        for (ProductStatusEnum statusEnum : ProductStatusEnum.values()) {
            if (statusEnum.getStatusCode().equals(statusCode)) {
                return statusEnum;
            }
        }
        return null;
    }
}

业务逻辑调用:

String productStatus = ProductStatusEnum.of("1").getProductStatus();

6.利用lamda表达式

现在有如下这段代码:

public String getMessage(String str) {
        String message = null;
        if (str.equals("1")) {
            message = "代码是1";
        } else if (str.equals("2")) {
            message = "代码是2";
        } else if (str.equals("3")) {
            message = "代码是3";
        } else if (str.equals("4")) {
            message = "代码是4";
        } else if (str.equals("5")) {
            message = "代码是5";
        }
        return message;
    }

利用lamda表达式进行优化:

public Map<String, Supplier> handleMessage() {
        Map<String, Supplier> map = new ConcurrentHashMap<String, Supplier>();
        map.put("1", () -> {
            return "代码是1";
        });
        map.put("2", () -> {
            return "代码是2";
        });
        map.put("3", () -> {
            return "代码是3";
        });
        map.put("4", () -> {
            return "代码是4";
        });
        map.put("5", () -> {
            return "代码是5";
        });
        return map;
    }

方法调用:

public String getMessage(String str) {
        String message = null;
        message = (String) handleMessage().get(str).get();
        return message;
    }

需要注意的是:当调用 handleMessage().get(str) 为 null 时,此时程序会报空指针异常,如下图:

在这里插入图片描述
所以在调用时,最好在经过一层空判断处理:

public String getMessage(String str) {
        String message = null;
        if (handleMessage().get(str) != null) {
            message = (String) handleMessage().get(str).get();
        }
        return message;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YD_1989

分享不易,非常感谢您的鼓励支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值