策略模式的三个主要组成部分:策略接口/父类、具体策略类、策略上下文
1.策略接口/父类(Strategy Interface)
这是一个接口,定义了一个方法或一系列方法,所有的策略类都必须实现这个接口。
public abstract class PayServiceNew {
String MSG = "使用 %s ,消费了 %s 元";
abstract String pay(String amount);
abstract PayEnum getPayEnum();
//判断是否支持该支付方式
boolean support(String channel) {
return this.getPayEnum().getChannel().equals(channel);
}
}
2.具体策略类(Concrete Strategy Classes)
实现策略接口的类,负责具体实现。
// 支付宝支付
@Service
public class AliPayService extends PayServiceNew {
@Override
public String pay( String amount) {
return String.format(MSG, this.getPayEnum().getDescription(),amount);
}
@Override
public PayEnum getPayEnum() {
return PayEnum.ALI_PAY;
}
}
// 微信支付
@Service
public class WechatPayService extends PayServiceNew {
@Override
public String pay(String amount) {
return String.format(MSG, this.getPayEnum().getDescription(), amount);
}
@Override
public PayEnum getPayEnum() {
return PayEnum.WECHAT_PAY;
}
}
3.上下文类(Context Class)
包含了所有策略,根据不同策略入参,执行不同策略
@Component
@RequiredArgsConstructor
public class StrategyContext {
public String pay(String channel, String amount) {
List<PayServiceNew> payServiceNewList = SpringContextUtil.getBeansOfType(PayServiceNew.class);
for (PayServiceNew payServiceNew : payServiceNewList) {
if (payServiceNew.support(channel)) {
return payServiceNew.pay(amount);
}
}
return "输入渠道码有误";
}
}
4.使用策略
@RestController
@RequestMapping("/xiaoniu")
public class PayController {
@Resource
private StrategyContext strategyContext;
@RequestMapping("/strategy/pay")
public String strategyPay(@RequestParam(name = "channel") String channel, @RequestParam(name = "amount") String amount) throws Exception {
return strategyContext.pay(channel, amount);
}
}