Spring自动注入使用工厂策略模式实战



前言

通过使用工厂策略设计模式有很多好处,例如代码解耦,更好的维护、省去很多if....else判断。


一、使用步骤

场景是我们可能会对接很对支付,每种支付逻辑都不相同.接下来直接看代码

我们新建一个接口

public interface PayServiceStrategy {

    Boolean pay(BigDecimal money);

}

我们定义一个抽象类,里面放一些支付公共的东西,如果没有公共的东西就不需要这个类了

@Service
public abstract class PayAbstractService implements PayServiceStrategy {

    protected void saveData(){

    }

}

接下来就是具体实现类


@Service
public class WeiXinPayService extends PayAbstractService {

    @Override
    public Boolean pay(BigDecimal money) {
         //业务逻辑
        System.out.println("微信支付了"+money+"元");
        return true;
    }
}
@Service
public class AilBaBaPayService extends PayAbstractService {

    @Override
    public Boolean pay(BigDecimal money) {
        this.saveData();
        System.out.println("支付宝支付了"+money+"元");
        //业务逻辑
        return true;
    }
}

我们需要定义一个枚举去找到实现类

@Getter
public enum PayType {

    WEI_XIN(1,"微信支付","weiXinPayService"),AIL_BA_BA(2,"支付宝支付","ailBaBaPayService");

    PayType(Integer code, String desc, String strategy) {
        this.code = code;
        this.desc = desc;
        this.strategy = strategy;
    }

    private Integer code;

    private String desc;

    private String strategy;
}

然后我们看看怎样使用,编写controller太费事我就在单元测试中测试下


    @Autowired
    private Map<String, PayServiceStrategy> strategyMap = new ConcurrentHashMap<>();

    @Test
    public void pay(){
        //假如前端传过来的支付类型是微信
        PayType payType = PayType.WEI_XIN;
        BigDecimal money = new BigDecimal("111");
        //调用相关实现类方法
        strategyMap.get(payType.getStrategy()).pay(money);
    }

运行结果

Spring自动注入使用工厂策略模式实战

  @Autowired
    private Map<String, PayServiceStrategy> strategyMap = new ConcurrentHashMap<>();

这个主要用到了spring的接口注入,很好用,不需要我们手动写策略类去找,很是方便,非常好用

上一篇:第三方支付宝支付(非真实金额支付)


下一篇:支付宝支付