Java 中如何优化大量的 if...else...

柔光的暖阳◎ 2023-09-25 17:34 177阅读 0赞

策略模式(Strategy Pattern)

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

示例:

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

  1. public interface PaymentStrategy {
  2. void pay(double amount);
  3. }

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

  1. public class CreditCardPaymentStrategy implements PaymentStrategy {
  2. private String name;
  3. private String cardNumber;
  4. private String cvv;
  5. private String dateOfExpiry;
  6. public CreditCardPaymentStrategy(String name, String cardNumber, String cvv, String dateOfExpiry) {
  7. this.name = name;
  8. this.cardNumber = cardNumber;
  9. this.cvv = cvv;
  10. this.dateOfExpiry = dateOfExpiry;
  11. }
  12. public void pay(double amount) {
  13. System.out.println(amount + " paid with credit card");
  14. }
  15. }
  16. public class PayPalPaymentStrategy implements PaymentStrategy {
  17. private String emailId;
  18. private String password;
  19. public PayPalPaymentStrategy(String emailId, String password) {
  20. this.emailId = emailId;
  21. this.password = password;
  22. }
  23. public void pay(double amount) {
  24. System.out.println(amount + " paid using PayPal");
  25. }
  26. }
  27. public class CashPaymentStrategy implements PaymentStrategy {
  28. public void pay(double amount) {
  29. System.out.println(amount + " paid in cash");
  30. }
  31. }

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

  1. public class ShoppingCart {
  2. private List<Item> items;
  3. public ShoppingCart() {
  4. this.items = new ArrayList<>();
  5. }
  6. public void addItem(Item item) {
  7. this.items.add(item);
  8. }
  9. public void removeItem(Item item) {
  10. this.items.remove(item);
  11. }
  12. public double calculateTotal() {
  13. double sum = 0;
  14. for (Item item : items) {
  15. sum += item.getPrice();
  16. }
  17. return sum;
  18. }
  19. public void pay(PaymentStrategy paymentStrategy) {
  20. double amount = calculateTotal();
  21. paymentStrategy.pay(amount);
  22. }
  23. }

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

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

工厂模式(Factory Pattern)

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

示例:

  1. // 定义一个接口
  2. public interface StringProcessor {
  3. public void processString(String str);
  4. }
  5. // 实现接口的具体类
  6. public class LowercaseStringProcessor implements StringProcessor {
  7. public void processString(String str) {
  8. System.out.println(str.toLowerCase());
  9. }
  10. }
  11. public class UppercaseStringProcessor implements StringProcessor {
  12. public void processString(String str) {
  13. System.out.println(str.toUpperCase());
  14. }
  15. }
  16. public class ReverseStringProcessor implements StringProcessor {
  17. public void processString(String str) {
  18. StringBuilder sb = new StringBuilder(str);
  19. System.out.println(sb.reverse().toString());
  20. }
  21. }
  22. // 工厂类
  23. public class StringProcessorFactory {
  24. public static StringProcessor createStringProcessor(String type) {
  25. if (type.equals("lowercase")) {
  26. return new LowercaseStringProcessor();
  27. } else if (type.equals("uppercase")) {
  28. return new UppercaseStringProcessor();
  29. } else if (type.equals("reverse")) {
  30. return new ReverseStringProcessor();
  31. }
  32. throw new IllegalArgumentException("Invalid type: " + type);
  33. }
  34. }
  35. // 测试代码
  36. public class Main {
  37. public static void main(String[] args) {
  38. StringProcessor sp1 = StringProcessorFactory.createStringProcessor("lowercase");
  39. sp1.processString("Hello World");
  40. StringProcessor sp2 = StringProcessorFactory.createStringProcessor("uppercase");
  41. sp2.processString("Hello World");
  42. StringProcessor sp3 = StringProcessorFactory.createStringProcessor("reverse");
  43. sp3.processString("Hello World");
  44. }
  45. }

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

映射表(Map)

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

示例:

  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.function.Function;
  4. public class MappingTableExample {
  5. private Map<String, Function<Integer, Integer>> functionMap;
  6. public MappingTableExample() {
  7. functionMap = new HashMap<>();
  8. functionMap.put("add", x -> x + 1);
  9. functionMap.put("sub", x -> x - 1);
  10. functionMap.put("mul", x -> x * 2);
  11. functionMap.put("div", x -> x / 2);
  12. }
  13. public int calculate(String operation, int input) {
  14. if (functionMap.containsKey(operation)) {
  15. return functionMap.get(operation).apply(input);
  16. } else {
  17. throw new IllegalArgumentException("Invalid operation: " + operation);
  18. }
  19. }
  20. public static void main(String[] args) {
  21. MappingTableExample example = new MappingTableExample();
  22. System.out.println(example.calculate("add", 10));
  23. System.out.println(example.calculate("sub", 10));
  24. System.out.println(example.calculate("mul", 10));
  25. System.out.println(example.calculate("div", 10));
  26. System.out.println(example.calculate("mod", 10)); // 抛出异常
  27. }
  28. }

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

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

示例:

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.function.Function;
  4. public class DataDrivenDesignExample {
  5. private List<Function<Integer, Integer>> functionList;
  6. public DataDrivenDesignExample() {
  7. functionList = new ArrayList<>();
  8. functionList.add(x -> x + 1);
  9. functionList.add(x -> x - 1);
  10. functionList.add(x -> x * 2);
  11. functionList.add(x -> x / 2);
  12. }
  13. public int calculate(int operationIndex, int input) {
  14. if (operationIndex < 0 || operationIndex >= functionList.size()) {
  15. throw new IllegalArgumentException("Invalid operation index: " + operationIndex);
  16. }
  17. return functionList.get(operationIndex).apply(input);
  18. }
  19. public static void main(String[] args) {
  20. DataDrivenDesignExample example = new DataDrivenDesignExample();
  21. System.out.println(example.calculate(0, 10));
  22. System.out.println(example.calculate(1, 10));
  23. System.out.println(example.calculate(2, 10));
  24. System.out.println(example.calculate(3, 10));
  25. System.out.println(example.calculate(4, 10)); // 抛出异常
  26. }
  27. }

发表评论

表情:
评论列表 (有 0 条评论,177人围观)

还没有评论,来说两句吧...

相关阅读