本文共 2314 字,大约阅读时间需要 7 分钟。
在订单支付场景中,选择多种支付方式(如支付宝、微信、银联等)会导致代码臃肿,难以维护。为了解决这个问题,可以采用策略模式来优化代码结构,使其更易维护且扩展性强。
原始代码中,订单类使用if-else语句处理支付方式选择,代码结构复杂且难以扩展,违背了开闭原则。
定义一个支付接口,所有支付方式类都实现该接口。
public interface Payment { boolean pay(String orderId, long amount);} 分别创建支付宝、微信、银联等支付方式的具体策略类。
public class AliPay implements Payment { @Override public boolean pay(String orderId, long amount) { System.out.println("支付宝支付,订单号:" + orderId + " 金额:" + amount); return true; }} public class WeChatPay implements Payment { @Override public boolean pay(String orderId, long amount) { System.out.println("微信支付,订单号:" + orderId + " 金额:" + amount); return true; }} 订单类持有支付策略接口的引用,并调用其方法。
public class Order { private String orderId; private long amount; private Payment payType; public Order(String orderId, Payment payType, long amount) { this.orderId = orderId; this.payType = payType; this.amount = amount; } public boolean pay() { boolean result = payType.pay(orderId, amount); if (!result) { System.out.println("支付失败"); } return result; }} 工厂类用于根据支付方式名称获取相应的支付策略。
public class PayStrategyFactory { private static Map paymentStrategyMap = new HashMap<>(); static { paymentStrategyMap.put("aliPay", new AliPay()); paymentStrategyMap.put("wechatPay", new WeChatPay()); paymentStrategyMap.put("unionPay", new UnionPay()); } public static Payment getPayment(String type) { return paymentStrategyMap.get(type); }} 客户端模拟前端传入支付方式,工厂获取策略,注入到订单类中。
public class OrderTest { @Test public void test() { String orderId = "123"; String payType = "aliPay"; long amount = 200; Order order = new Order(orderId, payType, amount); order.pay(); }} 策略模式在以下场景中尤为适用:
通过引入策略模式,订单支付场景的代码结构得到了优化,支付方式的选择变得更加灵活和可维护。这一模式在需要频繁更换或扩展支付方式时尤为重要,符合现代软件开发的最佳实践。
转载地址:http://lrbp.baihongyu.com/