java中优化大量if...else...方法总结

 更新时间:2023年03月18日 10:26:23   作者:提笔忘字的帝国  
在我们平时的开发过程中,经常可能会出现大量If else的场景,代码显的很臃肿,非常不优雅,下面这篇文章主要给大家介绍了关于java中优化大量if...else...方法的相关资料,需要的朋友可以参考下

策略模式(Strategy Pattern)

将每个条件分支的实现作为一个独立的策略类,然后使用一个上下文对象来选择要执行的策略。这种方法可以将大量的if else语句转换为对象之间的交互,从而提高代码的可维护性和可扩展性。

示例:

 首先,我们定义一个接口来实现所有策略的行为:

public interface PaymentStrategy {
    void pay(double amount);
}

接下来,我们定义具体的策略类来实现不同的支付方式: 

public class CreditCardPaymentStrategy implements PaymentStrategy {
    private String name;
    private String cardNumber;
    private String cvv;
    private String dateOfExpiry;
 
    public CreditCardPaymentStrategy(String name, String cardNumber, String cvv, String dateOfExpiry) {
        this.name = name;
        this.cardNumber = cardNumber;
        this.cvv = cvv;
        this.dateOfExpiry = dateOfExpiry;
    }
 
    public void pay(double amount) {
        System.out.println(amount + " paid with credit card");
    }
}
 
public class PayPalPaymentStrategy implements PaymentStrategy {
    private String emailId;
    private String password;
 
    public PayPalPaymentStrategy(String emailId, String password) {
        this.emailId = emailId;
        this.password = password;
    }
 
    public void pay(double amount) {
        System.out.println(amount + " paid using PayPal");
    }
}
 
public class CashPaymentStrategy implements PaymentStrategy {
    public void pay(double amount) {
        System.out.println(amount + " paid in cash");
    }
}

现在,我们可以在客户端代码中创建不同的策略对象,并将它们传递给一个统一的支付类中,这个支付类会根据传入的策略对象来调用相应的支付方法: 

public class ShoppingCart {
    private List<Item> items;
 
    public ShoppingCart() {
        this.items = new ArrayList<>();
    }
 
    public void addItem(Item item) {
        this.items.add(item);
    }
 
    public void removeItem(Item item) {
        this.items.remove(item);
    }
 
    public double calculateTotal() {
        double sum = 0;
        for (Item item : items) {
            sum += item.getPrice();
        }
        return sum;
    }
 
    public void pay(PaymentStrategy paymentStrategy) {
        double amount = calculateTotal();
        paymentStrategy.pay(amount);
    }
}

现在我们可以使用上述代码来创建一个购物车,向其中添加一些商品,然后使用不同的策略来支付: 

public class Main {
    public static void main(String[] args) {
        ShoppingCart cart = new ShoppingCart();
 
        Item item1 = new Item("1234", 10);
        Item item2 = new Item("5678", 40);
 
        cart.addItem(item1);
        cart.addItem(item2);
 
        // pay by credit card
        cart.pay(new CreditCardPaymentStrategy("John Doe", "1234567890123456", "786", "12/22"));
 
        // pay by PayPal
        cart.pay(new PayPalPaymentStrategy("myemail@example.com", "mypassword"));
 
        // pay in cash
        cart.pay(new CashPaymentStrategy());
 
        //--------------------------或者提前将不同的策略对象放入map当中,如下
 
        Map<String, PaymentStrategy> paymentStrategies = new HashMap<>();
 
        paymentStrategies.put("creditcard", new CreditCardPaymentStrategy("John Doe", "1234567890123456", "786", "12/22"));
        paymentStrategies.put("paypal", new PayPalPaymentStrategy("myemail@example.com", "mypassword"));
        paymentStrategies.put("cash", new CashPaymentStrategy());
 
        String paymentMethod = "creditcard"; // 用户选择的支付方式
        PaymentStrategy paymentStrategy = paymentStrategies.get(paymentMethod);
 
        cart.pay(paymentStrategy);
 
    }
}

工厂模式(Factory Pattern)

将每个条件分支的实现作为一个独立的产品类,然后使用一个工厂类来创建具体的产品对象。这种方法可以将大量的if else语句转换为对象的创建过程,从而提高代码的可读性和可维护性。

示例: 

// 定义一个接口
public interface StringProcessor {
    public void processString(String str);
}
 
// 实现接口的具体类
public class LowercaseStringProcessor implements StringProcessor {
    public void processString(String str) {
        System.out.println(str.toLowerCase());
    }
}
 
public class UppercaseStringProcessor implements StringProcessor {
    public void processString(String str) {
        System.out.println(str.toUpperCase());
    }
}
 
public class ReverseStringProcessor implements StringProcessor {
    public void processString(String str) {
        StringBuilder sb = new StringBuilder(str);
        System.out.println(sb.reverse().toString());
    }
}
 
// 工厂类
public class StringProcessorFactory {
    public static StringProcessor createStringProcessor(String type) {
        if (type.equals("lowercase")) {
            return new LowercaseStringProcessor();
        } else if (type.equals("uppercase")) {
            return new UppercaseStringProcessor();
        } else if (type.equals("reverse")) {
            return new ReverseStringProcessor();
        }
        throw new IllegalArgumentException("Invalid type: " + type);
    }
}
 
// 测试代码
public class Main {
    public static void main(String[] args) {
        StringProcessor sp1 = StringProcessorFactory.createStringProcessor("lowercase");
        sp1.processString("Hello World");
        
        StringProcessor sp2 = StringProcessorFactory.createStringProcessor("uppercase");
        sp2.processString("Hello World");
        
        StringProcessor sp3 = StringProcessorFactory.createStringProcessor("reverse");
        sp3.processString("Hello World");
    }
}

 看起来还是有if...else,但这样的代码更加简洁易懂,后期也便于维护....

映射表(Map)

使用一个映射表来将条件分支的实现映射到对应的函数或方法上。这种方法可以减少代码中的if else语句,并且可以动态地更新映射表,从而提高代码的灵活性和可维护性。 

示例:

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
 
public class MappingTableExample {
    private Map<String, Function<Integer, Integer>> functionMap;
 
    public MappingTableExample() {
        functionMap = new HashMap<>();
        functionMap.put("add", x -> x + 1);
        functionMap.put("sub", x -> x - 1);
        functionMap.put("mul", x -> x * 2);
        functionMap.put("div", x -> x / 2);
    }
 
    public int calculate(String operation, int input) {
        if (functionMap.containsKey(operation)) {
            return functionMap.get(operation).apply(input);
        } else {
            throw new IllegalArgumentException("Invalid operation: " + operation);
        }
    }
 
    public static void main(String[] args) {
        MappingTableExample example = new MappingTableExample();
        System.out.println(example.calculate("add", 10));
        System.out.println(example.calculate("sub", 10));
        System.out.println(example.calculate("mul", 10));
        System.out.println(example.calculate("div", 10));
        System.out.println(example.calculate("mod", 10)); // 抛出异常
    }
}

数据驱动设计(Data-Driven Design) 

将条件分支的实现和输入数据一起存储在一个数据结构中,然后使用一个通用的函数或方法来处理这个数据结构。这种方法可以将大量的if else语句转换为数据结构的处理过程,从而提高代码的可扩展性和可维护性。 

示例:

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
 
public class DataDrivenDesignExample {
    private List<Function<Integer, Integer>> functionList;
 
    public DataDrivenDesignExample() {
        functionList = new ArrayList<>();
        functionList.add(x -> x + 1);
        functionList.add(x -> x - 1);
        functionList.add(x -> x * 2);
        functionList.add(x -> x / 2);
    }
 
    public int calculate(int operationIndex, int input) {
        if (operationIndex < 0 || operationIndex >= functionList.size()) {
            throw new IllegalArgumentException("Invalid operation index: " + operationIndex);
        }
        return functionList.get(operationIndex).apply(input);
    }
 
    public static void main(String[] args) {
        DataDrivenDesignExample example = new DataDrivenDesignExample();
        System.out.println(example.calculate(0, 10));
        System.out.println(example.calculate(1, 10));
        System.out.println(example.calculate(2, 10));
        System.out.println(example.calculate(3, 10));
        System.out.println(example.calculate(4, 10)); // 抛出异常
    }
}

总结

到此这篇关于java中优化大量if...else...的文章就介绍到这了,更多相关java优化大量if...else...内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 浅谈基于SpringBoot实现一个简单的权限控制注解

    浅谈基于SpringBoot实现一个简单的权限控制注解

    这篇文章主要介绍了基于SpringBoot实现一个简单的权限控制注解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • Spring Boot2.x集成JPA快速开发的示例代码

    Spring Boot2.x集成JPA快速开发的示例代码

    这篇文章主要介绍了Spring Boot2.x集成JPA快速开发,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-05-05
  • SpringBoot中使用MyBatis-Plus详细步骤

    SpringBoot中使用MyBatis-Plus详细步骤

    MyBatis-Plus是MyBatis的增强工具,简化了MyBatis的使用,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧
    2025-01-01
  • Java虚拟机精选面试题20道

    Java虚拟机精选面试题20道

    现在面试Java开发时,基本都会问到Java虚拟机的知识,根据职位不同问的内容深浅又有所区别。本文整理了10道面试中常问的Java虚拟机面试题,希望对正在面试的同学有所帮助
    2021-06-06
  • SpringBoot结合WebSocket实现聊天功能

    SpringBoot结合WebSocket实现聊天功能

    本文介绍了如何使用SpringBoot和WebSocket实现一个简单的聊天功能,包括导入依赖、配置类、创建消息实体、指定ServerEndpoint、创建客户端等步骤,通过具体示例,演示了如何发送个人消息和群发消息,实现了基本的聊天功能,适合需要在项目中实现实时通讯功能的开发者参考
    2024-11-11
  • Java中synchronized 的4个优化技巧

    Java中synchronized 的4个优化技巧

    本文主要介绍了Java中synchronized的4个优化技巧,synchronized在JDK 1.5 时性能是比较低的,然而在后续的版本中经过各种优化迭代,它的性能也得到了前所未有的提升,下文更多相关资料需要的小伙伴可以参考一下
    2022-05-05
  • 如何用Spring发送电子邮件

    如何用Spring发送电子邮件

    这篇文章主要介绍了如何用Spring发送电子邮件,帮助大家更好的理解和使用Java,感兴趣的朋友可以了解下
    2021-02-02
  • spring boot加载freemarker模板路径的方法

    spring boot加载freemarker模板路径的方法

    这篇文章主要介绍了spring boot加载freemarker模板路径的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-11-11
  • springboot打成jar后无法读取根路径和文件的解决

    springboot打成jar后无法读取根路径和文件的解决

    这篇文章主要介绍了springboot打成jar后无法读取根路径和文件的解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-12-12
  • Minio环境部署过程及如何配置HTTPS域名

    Minio环境部署过程及如何配置HTTPS域名

    MinIO 是一个对象存储系统,数据需要存储在宿主机上,容器的重启不影响数据,因此我们需要为 MinIO 创建一个挂载目录,用于持久化存储数据,本文详细介绍了如何部署MinIO,并通过配置反向代理和HTTPS来提升其安全性,感兴趣的朋友一起看看吧
    2025-03-03

最新评论