策略模式结合Spring使用

1.抽象策略

/**
 * 支付方式策略
 * @author Linging
 * @version 1.0.0
 * @since 1.0
 */
public interface PayStrategy {

    void pay(BigDecimal money);

}

2.具体策略

/**
 * 支付宝
 * @author Linging
 * @version 1.0.0
 * @since 1.0
 */
@Component("aliPayStrategy")
public class AliPayStrategy implements PayStrategy{
    @Override
    public void pay(BigDecimal money) {
        System.out.println("使用支付宝支付了 " + money + " 元");
    }
}
/**
 * 微信支付
 * @author Linging
 * @version 1.0.0
 * @since 1.0
 */
@Component("weChatPayStrategy")
public class WeChatPayStrategy implements PayStrategy{
    @Override
    public void pay(BigDecimal money) {
        System.out.println("使用微信支付了 " + money + " 元");
    }
}
/**
 * 信用卡支付
 * @author Linging
 * @version 1.0.0
 * @since 1.0
 */
@Component("creditCardPayStrategy")
public class CreditCardPayStrategy implements PayStrategy{
    @Override
    public void pay(BigDecimal money) {
        System.out.println("使用信用卡支付了 " + money + " 元");
    }
}

3.工厂配置策略

/**
 * 配置策略
 * @author Linging
 * @version 1.0.0
 * @since 1.0
 */
@Component
public class PayContentFactory {

    @Resource
    private ApplicationContext context;

    private Map<Integer, PayStrategy> map = new HashMap<>();

    @PostConstruct
    public void init(){
        for (PayEnum payEnum : PayEnum.values()) {
            map.putIfAbsent(payEnum.getCode(),
                    context.getBean(payEnum.getBeanName(), PayStrategy.class));
        }
    }

    public PayStrategy getPayStrategyPay(PayEnum payEnum){
        return map.get(payEnum.getCode());
    }

}

4.枚举

/**
 * @author Linging
 * @version 1.0.0
 * @since 1.0
 */
public enum PayEnum {

    ALI(1, "支付宝", "aliPayStrategy"),
    WECHAT(2, "微信", "weChatPayStrategy"),
    CREDIT_CARD(3, "信用卡", "creditCardPayStrategy"),
    ;

    int code;

    String remark;

    String beanName;

    PayEnum(int code, String remark, String beanName) {
        this.code = code;
        this.remark = remark;
        this.beanName = beanName;
    }

    public int getCode() {
        return code;
    }

    public String getRemark() {
        return remark;
    }

    public String getBeanName() {
        return beanName;
    }
}

5.使用

    @Resource
    private PayContentFactory payContentFactory;

    @GetMapping("/testStrategy")
    public String testStrategy(){

        payContentFactory.getPayStrategyPay(PayEnum.ALI).pay(new BigDecimal("100"));
        payContentFactory.getPayStrategyPay(PayEnum.WECHAT).pay(new BigDecimal("99"));
        payContentFactory.getPayStrategyPay(PayEnum.CREDIT_CARD).pay(new BigDecimal("88"));

        return "ok";
    }
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值