首页 > 编程语言 >Java 中如何优化大量的 if...else...

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

时间:2023-03-20 11:11:22浏览次数:32  
标签:... Java String System else println new public out

策略模式(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("[email protected]", "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("[email protected]", "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,String,System,else,println,new,public,out
From: https://www.cnblogs.com/johnny-ylp/p/17235612.html

相关文章

  • Java访问权限修饰符(public , private , protected)
    访问权限修饰符包括:public、protected、private和默认修饰符(friendly/包访问权限)。可以修饰在类、字段、方法前面。public:公开权限,所有类都可以访问。protected:继承访......
  • java 项目使用 本地的gradle wrapper 或者 mvn gradle
    使用ganradle的好处是当前项目对版本idea自动下载mvnwrapper目录结构.mvnwrappermaven-wrapper.jarmaven-wrapper.propertiesMaven......
  • java-基础线程机制
     前言,基础线程机制:Executor管理多个异步任务的执行、Daemon守护线程、sleep()、yield() 一、Executor:1.newCachedThreadPool(),一个任务创建一个线程ExecutorServic......
  • Java基础语法-数组
    第一部分:数组1.数组1.1数组介绍数组就是存储数据长度固定的容器,存储多个数据的数据类型要一致。1.2数组的定义格式1.2.1第一种格式数据类型[]数组名示例:int[]arr......
  • 【Java】Mybatis Plus LambdaQueryWrapper梳理
    【Java】Mybatis-PlusLambdaQueryWrapper梳理前言为了更方便的实现动态SQL,MybatisPlus在其基础上扩展了LambdaQueryWrapper,LambdaQueryWrapper提供了​​更加简便的查......
  • 使用工厂模式+策略模式+模板方法实现对大量if...else的改造
    1.策略模式+工厂模式+模板模式实际开发工程中,一些业务很复杂的逻辑使用很多的if或者if···else语句,不利于维护和扩展,为了使代码更加优雅,利于维护可以采用策略模式+......
  • Tars-Java网络编程源码分析
    作者:vivo互联网服务器团队-JinKai本文从JavaNIO网络编程的基础知识讲到了Tars框架使用NIO进行网络编程的源码分析。一、Tars框架基本介绍Tars是腾讯开源的支持多语言的......
  • Playwright+JavaScript-1.环境准备与快速开始
    前言Playwright可以支持在TypeScript、JavaScript、Python、.NET、Java中使用,本系列以JavaScript语言为示例。环境准备1.安装node.js需要Node.js14或更高版本2......
  • Java stream sorted自定义排序规则实现多字段排序
      Stream提供了丰富的操作(中间操作和终端操作)集合元素的轮子,但Stream流操作不影响原始集合数据,执行结果是一个新的集合对象。在《Javastreamsorted使用Comparator进......
  • java反射机制原理及应用
    java反射机制反射机制原理示意图​ Class.forName(字节码文件)类.class对象.getClass()用法:根据配置的properties文件(不仅是properties)从而无需修改源代码的情......