1.抽象策略
public interface PayStrategy {void pay(BigDecimal money);}
2.具体策略
@Component("aliPayStrategy")
public class AliPayStrategy implements PayStrategy{@Overridepublic void pay(BigDecimal money) {System.out.println("使用支付宝支付了 " + money + " 元");}
}
@Component("weChatPayStrategy")
public class WeChatPayStrategy implements PayStrategy{@Overridepublic void pay(BigDecimal money) {System.out.println("使用微信支付了 " + money + " 元");}
}
@Component("creditCardPayStrategy")
public class CreditCardPayStrategy implements PayStrategy{@Overridepublic void pay(BigDecimal money) {System.out.println("使用信用卡支付了 " + money + " 元");}
}
3.工厂配置策略
@Component
public class PayContentFactory {@Resourceprivate ApplicationContext context;private Map<Integer, PayStrategy> map = new HashMap<>();@PostConstructpublic 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.枚举
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.使用
@Resourceprivate 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";}