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

2023-05-16

策略模式(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)); // 抛出异常
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java 中如何优化大量的 if...else... 的相关文章

随机推荐

  • cookie与session

    a 什么是cookie 浏览器在访问服务器时 xff0c 服务器将一些数据以set cookie 消息头 的形式发送给浏览器 浏览器会将这些数据保存起来 当浏览器再次访问服务器时 xff0c 会将这些数据以cookie消息头的形式发送给服务
  • GithubDNS解析配置

    hosts文件位置 xff1a Windows 系统 xff1a C Windows System32 drivers etc hosts 复制以下代码 xff1a GitHub520 Host Start 140 82 114 26 al
  • java:如何判断一个链表是否成环,并找到成环的位置

    面试题型 xff1a 判断一个链表中是否成环 思路 xff1a 定义两个快慢指针 xff0c 让他们一直移动 xff0c 如果最终快指针 61 慢指针 xff0c 这说明在这个链表中必然存在环 首先 xff0c 将快指针定义为fast 慢指
  • 基于zynq7000平台的vxWorks6.9移植(上)

    1 致谢 编写本文档的目的在于指导用户如何移植基于z7平台的vxWorks6 9系统 移植之前首先感谢西安迅尔电子嵌入式工程师庞国强 xff0c 本次是基于前者总结资料的基础上进行的完善 xff0c 帮助新手可以以更少的指导掌握z7平台关于
  • Python新建、写入和修改txt(文本文档)

    新建 写入 xff1a 创建一个txt文件 xff0c 文件名为first file 并向文件写入msg def File New name msg desktop path 61 34 路径 34 文件路径 full path 61 de
  • 面试突击:输入URL之后会执行什么流程?

    在浏览器中输入 URL 之后 xff0c 它会执行以下几个流程 xff1a 执行 DNS 域名解析 xff1b 封装 HTTP 请求数据包 xff1b 封装 TCP 请求数据包 xff1b 建立 TCP 连接 xff08 3 次握手 xff
  • 面试官:Spring Aop 常见注解和执行顺序

    最近 xff0c 我在给很多人做简历修改和模拟面试的时候 xff0c 有部分朋友和我反馈Spring AOP的面试题 xff0c 今天就和大家来问问 Spring 一开始最强大的就是 IOC AOP 两大核心功能 xff0c 我们今天一起来
  • Microsoft Visual C++ 14.0下载方法

    去官网下载对应的文件 xff08 需要拥有一个微软的账号 xff09 首先 xff0c 打开链接首页 Visual Studio Subscriptions Portal xff0c 登录账号 xff0c 点击进入下载页面 接下来 xff0
  • Zabbix6.0离线安装(附RPM包)

    zabbix server6 0安装包及依赖 一 准备工作 xff1a 虚拟环境软件VMware Workstation 17 pro xff0c 可以根据自身需求来选择 xff0c VMware下载链接参考如下 xff1a https c
  • java中try 与catch的使用

    try 代码区 catch Exception e 异常处理 代码区如果有错误 xff0c 就会返回所写异常的处理 首先要清楚 xff0c 如果没有try的话 xff0c 出现异常会导致程序崩溃 而try则可以保证程序的正常运行下去 xff
  • 基于JAVA京津冀畅游网设计计算机毕业设计源码+数据库+lw文档+系统+部署

    基于JAVA京津冀畅游网设计计算机毕业设计源码 43 数据库 43 lw文档 43 系统 43 部署 基于JAVA京津冀畅游网设计计算机毕业设计源码 43 数据库 43 lw文档 43 系统 43 部署 本源码技术栈 xff1a 项目架构
  • JSP 四大作用域:

    application对象中的属性可以被同一个WEB应用程序中的所有Servlet和JSP页面访问 xff08 属性作用范围最大 xff09 session对象中的属性可以被属于同一个会话的所有Servlet和JSP页面访问 xff08 适
  • django基于Python的疫情数据可视化分析系统的设计与实现(源码调试+代码讲解+文档报告)

    x1f495 x1f495 作者 xff1a 计算机源码社 x1f495 x1f495 个人简介 xff1a 本人七年开发经验 xff0c 擅长Java 微信小程序 Python Android等 xff0c 大家有这一块的问题可以一起交流
  • 基于SSM+Vue个人健康信息管理系统Java个人健康状况记录与评估系统(源码调试+讲解+文档)

    x1f495 x1f495 作者 xff1a 计算机源码社 x1f495 x1f495 个人简介 xff1a 本人七年开发经验 xff0c 擅长Java 微信小程序 Python Android等 xff0c 大家有这一块的问题可以一起交流
  • DBSCAN聚类——Python实现

    一 DBSCAN Density Baseed Spatial Clustering of Applications with Noise 聚类算法 核心对象 xff1a 若某个点的密度达到算法设定的阈值则其为核心 xff08 即r邻域内点
  • 解决ubuntu操作系统默认没有创建root账户

    解决ubuntu操作系统默认没有创建root账户 xff1a 1 sudo passwd root重置root密码 会提示输入当前用户密码 xff0c 然后重新设置新密码 2 设置成功之后su root得到root登陆
  • hexo+github个人博客搭建(亲身经历超详解)

    Hexo 是一个快速 简洁且高效的博客框架 Hexo 使用 Markdown xff08 或其他渲染引擎 xff09 解析文章 xff0c 在几秒内 xff0c 即可利用靓丽的主题生成静态网页 本文章适用于windows系统搭建 xff0c
  • 数论----质数的求解(C/C++)

    CSDN的uu xff0c 你们好呀 xff0c 今天我们要学习的内容是 数论 哦 xff01 这也是算法题中的一类题目吧 记好安全带 xff0c 准备发车咯 xff01 x1f680 学习数论的意义 x1f4e2 算法导论说 xff1a
  • 源代码是指什么?

    源代码是指以特定编程语言编写的文本文件 xff0c 用于控制软件 硬件 计算机程序或系统 源代码是代表软件不同功能的一类 指令 下面我将详细说明源代码的定义 首先要说的是 xff0c 源代码是建立在编程语言之上的文本文件 它可用于编写程序
  • Java 中如何优化大量的 if...else...

    策略模式 xff08 Strategy Pattern xff09 将每个条件分支的实现作为一个独立的策略类 xff0c 然后使用一个上下文对象来选择要执行的策略 这种方法可以将大量的if else语句转换为对象之间的交互 xff0c 从而