Java设计模式 之用策略+工厂模式替换业务复杂=if else

本文介绍了一种使用策略模式和工厂模式优化支付系统的方法,通过定义支付策略接口及其实现类,如超级VIP和普通会员策略,实现了根据不同用户类型动态选择支付策略的逻辑,避免了复杂的if-else判断。

策略接口:

import java.math.BigDecimal;

/**
 * 用户支付策略接口
 */
public interface UserPayStrategy {
    /**
     * 计算应付价格
     */
    BigDecimal quote(BigDecimal orderPrice);
}

策略实现类:

import org.springframework.stereotype.Service;
import java.math.BigDecimal;

/**
 * 超级VIP支付策略
 */
@Service
public class SuperVipPayStrategy implements UserPayStrategy {
    @Override
    public BigDecimal quote(BigDecimal orderPrice) {
        return orderPrice.multiply(new BigDecimal(0.8));
    }
}
///////////////////////////////////////////////////////////
import org.springframework.stereotype.Service;
import java.math.BigDecimal;

/**
 * 普通会员支付策略
 */
@Service
public class NormalVipPayStrategy implements UserPayStrategy{
    @Override
    public BigDecimal quote(BigDecimal orderPrice) {
        return orderPrice.multiply(new BigDecimal(0.9));
    }
}

获取策略的工厂:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
// 获取策略的工厂
@Component
public class UserPayServiceStrategyFactory {
    @Autowired
    private Map<String, UserPayStrategy> userPayStrategyMap;
    // 根据 name 获取策略实现,这里可以替换成相应的业务
    public UserPayStrategy getUserPayStrategy(String name){
        return userPayStrategyMap.get(name);
    }
}

通过策略工厂获取需要的策略后,执行业务逻辑:

UserPayStrategy strategy = userPayServiceStrategyFactory.getUserPayStrategy("normalVipPayStrategy");
strategy.quote(new BigDecimal(100)).toPlainString();

参考:
业务复杂=if else?刚来的大神竟然用策略+工厂彻底干掉了他们!

### 使用策略模式工厂模式优化代码 #### 策略模式概述 策略模式定义了一系列算法,并将每一个算法封装起来,使它们可以互相替换。此模式让算法独立于使用它的客户而变化[^1]。 #### 工厂模式的作用 当采用策略模式时,虽然减少了原本存在于业务逻辑中的`if-else`语句,但客户端仍需通过条件判断选择合适的策略实例。引入工厂模式能够有效解决这一问题,由专门的工厂类负责创建具体的策略对象,从而进一步简化了客户的操作流程[^2]。 #### 实现方式 下面展示了一个简单的例子,说明如何利用这两种模式组合来代替冗长的`if-else`结构: 假设有一个支付系统的场景,支持多种付款方式(信用卡、支付宝、微信),每种方式有不同的处理过程。 ```java // 定义策略接口 public interface PaymentStrategy { void pay(double amount); } // 具体策略实现 - 信用卡支付 public class CreditCardPayment implements PaymentStrategy { @Override public void pay(double amount) { System.out.println("Paid " + amount + " using Credit Card."); } } // 具体策略实现 - 支付宝支付 public class AlipayPayment implements PaymentStrategy { @Override public void pay(double amount) { System.out.println("Paid " + amount + " via Alipay."); } } // 具体策略实现 - 微信支付 public class WeChatPayPayment implements PaymentStrategy { @Override public void pay(double amount) { System.out.println("Paid " + amount + " through WeChat Pay."); } } ``` 接着构建一个工厂用于生产不同的支付策略: ```java // 创建策略工厂 public class PaymentFactory { private static final Map<String, PaymentStrategy> strategies = new HashMap<>(); static { strategies.put("CREDIT_CARD", new CreditCardPayment()); strategies.put("ALIPAY", new AlipayPayment()); strategies.put("WECHAT_PAY", new WeChatPayPayment()); } public static PaymentStrategy getPaymentMethod(String type){ return strategies.get(type.toUpperCase()); } } ``` 最后,在实际调用的地方只需要指定想要使用的支付方法名称即可完成支付动作,无需再编写复杂的条件分支: ```java String paymentType = getUserSelectedPaymentOption(); // 假设这是从前端获取到的选择项 double orderAmount = calculateOrderTotal(); PaymentStrategy selectedStrategy = PaymentFactory.getPaymentMethod(paymentType); selectedStrategy.pay(orderAmount); // 执行对应的支付行为 ``` 这种设计方案不仅提高了代码的可维护性和灵活性,还使得新增加一种新的支付手段变得非常容易——只需增加一个新的具体策略类并更新工厂内的映射关系表就可以了[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值