在复杂场景使用策略和工厂模式代替分支语句

在复杂场景使用策略和工厂模式代替分支语句

在软件开发过程中,随着业务逻辑的不断复杂,大量的分支语句往往会让代码变得臃肿、难以维护。而策略模式和工厂模式为我们提供了一种优雅的替代方案,能够有效地提升代码的可扩展性和可维护性。在复杂场景下,使用策略和工厂模式代替分支语句可以带来诸多好处。

在这里插入图片描述

直接上效果图

如果代码有几十个if-else是不是会很崩溃,但是使用策略工厂就能把if-else直接给优化掉。
在这里插入图片描述

策略工厂实现 - 支付案例

我是如何把上面的if-else优化掉的呢。仔细看完代码就会恍然大悟,相信我一定不会后悔。

一、定义策略接口

public interface PaymentStrategy {
    /**
     * 判断条件是否为true
     */
    boolean isSupport(String payMethod);

    /**
     * 支付方法
     */
    void pay(double amount);
}

二、实现对应的策略类

// 支付宝支付
public class AlipayPaymentStrategy implements PaymentStrategy {
    @Override
    public boolean isSupport(String payMethod) {
        return "AlipayPay".equals(payMethod);
    }

    @Override
    public void pay(double amount) {
        System.out.println("使用支付宝支付:" + amount + "元。");
    }
}

// paypal支付
public class PayPalPaymentStrategy implements PaymentStrategy {

    @Override
    public boolean isSupport(String payMethod) {
        return "PayPalPay".equals(payMethod);
    }

    @Override
    public void pay(double amount) {
        System.out.println("使用 PayPal 支付:" + amount + "元。");
    }
}

// 银联支付
public class UnionPayPaymentStrategy implements PaymentStrategy {
    @Override
    public boolean isSupport(String payMethod) {
        return "UnionPay".equals(payMethod);
    }

    @Override
    public void pay(double amount) {
        System.out.println("使用银联支付:" + amount + "元。");
    }
}


// 微信支付
public class WeChatPaymentStrategy implements PaymentStrategy {
    @Override
    public boolean isSupport(String payMethod) {
        return "WeChatPay".equals(payMethod);
    }

    @Override
    public void pay(double amount) {
        System.out.println("使用微信支付:" + amount + "元。");
    }
}

三、定义策略工厂

public class PaymentFactory {

    private final List<PaymentStrategy> paymentStrategyList = new ArrayList<>();

    private static final PaymentFactory factory = new PaymentFactory();

    /**
     * 单例工厂
     */
    public static PaymentFactory getInstance() {
        return factory;
    }

    private PaymentFactory() {
        // 注册策略
        paymentStrategyList.add(new AlipayPaymentStrategy());
        paymentStrategyList.add(new WeChatPaymentStrategy());
        paymentStrategyList.add(new UnionPayPaymentStrategy());
        paymentStrategyList.add(new PayPalPaymentStrategy());
        // 后续有策略,继续添加。也可以使用类扫描或者其他方式添加
    }

    /**
     * 从注册的策略列表中获取策略
     */
    public PaymentStrategy getStrategy(String payMethod) {
        for (PaymentStrategy paymentStrategy : paymentStrategyList) {
            if (paymentStrategy.isSupport(payMethod)) {
                return paymentStrategy;
            }
        }
        new Exception("支付方式不支持");
        return null;
    }
}

四、使用

   
   // 修改之后的使用方式
   public void strategyPay(double amount, String payMethod) {
        PaymentFactory paymentFactory = PaymentFactory.getInstance();
        PaymentStrategy strategy = paymentFactory.getStrategy(payMethod);
        strategy.pay(amount);
    }


    // 修改之前的使用方式
    public void pay(double amount, String payMethod) {
        if ("AlipayPay".equals(payMethod)) {
            System.out.println("使用支付宝支付:" + amount + "元。");
        } else if ("PayPalPay".equals(payMethod)) {
            System.out.println("使用 PayPal 支付:" + amount + "元。");
        } else if ("UnionPay".equals(payMethod)) {
            System.out.println("使用银联支付:" + amount + "元。");
        } else if ("WeChatPay".equals(payMethod)) {
            System.out.println("使用微信支付:" + amount + "元。");
        } else {
            new Exception("支付方式不支持");
        }
    }

五、接口测试

    @Test
    public void testStrategyPay() {
        paymentService.strategyPay(100.0, "AlipayPay");
        paymentService.strategyPay(100.0, "PayPalPay");
        paymentService.strategyPay(100.0, "UnionPay");
        paymentService.strategyPay(100.0, "WeChatPay");
    }

结果如下

使用支付宝支付:100.0元。
使用 PayPal 支付:100.0元。
使用银联支付:100.0元。
使用微信支付:100.0元。

if-else消失了吗

其实if-else看着是消失了,其实是转移到策略类中了。

可以看到策略类中有两个方法,一个方法对应条件,一个方法对应满足条件后的行为。

在这里插入图片描述

总结

当面对复杂场景时,大量的分支语句会让代码变得难以维护和理解。本文以支付案例为例,展示了如果代码中存在几十个if-else语句会带来的困扰。

通过引入策略和工厂模式,成功地将这些繁琐的if-else优化掉。在支付案例中,原本可能令人崩溃的条件判断被策略工厂巧妙替代,极大地提高了代码的可维护性和可读性。

仔细研究代码可以发现,策略模式将不同的支付方式封装成独立的策略类,而工厂模式则负责根据特定条件创建相应的策略对象。这种组合使得代码结构更加清晰,易于扩展和修改。

总之,在复杂场景下,策略和工厂模式为我们提供了一种有效的解决方案,帮助我们摆脱分支语句的困扰,提升软件的质量和可维护性。

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值