Strategy Pattern 简化了我的 Spring 系统的支付逻辑
Source: Dev.to
在这篇文章中,我将深入探讨一种设计模式,它解决了一个实际的软件架构挑战:需要根据响应中返回的付款类型,应用特定的执行模式来处理请求。对于每种付款方式,如信用卡、PayPal 等,需要执行不同的操作。
脱颖而出的解决方案是应用 Strategy 设计模式。它非常理想,因为它允许将每个处理逻辑隔离到各自的类(即它们的“策略”)中,使代码更简洁、易于维护,并且关键是对未来高度可扩展,以便在添加新的付款方式时能够轻松应对。
提醒:我展示的代码是对真实环境的简化,但重点在于架构解决方案的本质。
定义处理接口
第一步是为所有支付策略建立共同的契约。我创建了 PaymentProcessor 接口,它定义了将由每个专门的处理类实现的方法。
public interface PaymentProcessor {
boolean process(final PaymentResponse request);
}
管理策略的服务
接下来,我创建了 PaymentService 类,它是我们解决方案的核心。它的职责是映射并管理 PaymentProcessor 接口的所有实现。这使我们能够确定哪个类负责每种执行类型。在示例中,我从 PayPal 和信用卡策略开始。为了确保质量并严格控制支持的类型,我使用了名为 PaymentType 的 Enum,便于添加或移除新模式,例如未来的借记卡。
@Service
public class PaymentService {
private Map processors;
public PaymentService(@Qualifier("paypal") PaymentProcessor paypal,
@Qualifier("credit_card") PaymentProcessor credit) {
processors = Map.of(PaymentType.PAYPAL, paypal, PaymentType.CREDIT_CARD, credit);
}
public boolean process(String type, PaymentResponse request) {
PaymentType paymentType = PaymentType.valueOf(type.toUpperCase());
PaymentProcessor processor = processors.get(paymentType);
if (Objects.isNull(processor)) {
throw new IllegalArgumentException("Type not supported: " + type);
}
return processor.process(request);
}
}
public enum PaymentType {
PAYPAL, CREDIT_CARD, DEBIT_CARD
}
实现支付策略
现在,我们创建了 PayPalProcessor 和 CreditCardProcessor 类。两者都实现了 PaymentProcessor 接口。使用 Spring Boot 框架,这些类被标注,以便在启动应用时,框架能够识别它们并正确管理其 bean,将它们注入到 PaymentService 中。这样,PaymentService 将拥有所有已映射的策略并随时可用。
@Component
@Qualifier("paypal")
public class PayPalProcessor implements PaymentProcessor {
@Override
public boolean process(PaymentResponse request) {
System.out.println("✅ PayPal processed!");
return true;
}
}
@Component
@Qualifier("credit_card")
public class CreditCardProcessor implements PaymentProcessor {
@Override
public boolean process(PaymentResponse request) {
System.out.println("✅ credit card processed!");
return true;
}
}
执行与 IF 的终结
我们来到关键点:执行阶段。我们接收到 PaymentResponse(它模拟其他 API 的返回),其字段 paymentType 指明了我们正在处理的支付类型。PaymentService 随即介入,直接处理该信息。这里的最大优势是 消除了对条件块(if/else 或 switch/case)来检查支付类型的需求。
得益于 Spring Boot 的 Bean 管理,在请求时,PaymentService 只需根据提供的 paymentType 获取相应的策略并调用正确的方法。这种做法不仅提升了可维护性,还旨在实现 安全模式,防止 Java 中常见的错误,例如令人头疼的 NullPointerException。