项目场景:
支付时,需要根据用户选择的不同支付方式进行相应处理
实现方式
定义一个通用的支付接口及相应方法,并根据不同的支付方式编写相应的实现类,同时利用spring的自动注入机制(@Autowired),在bean注入时将所有实现类注入,并在执行时判断用户所选择的支付方式,然后进行相应的处理。
实现代码
策略接口
public interface IPaymentStrategy {
boolean accept(String paymentMethod);
void invokePay(Param param);
}
实现类
@Service("ALiPayment")
public class ALiPayment implements IPaymentStrategy {
@Override
public boolean accept(String paymentMethod) {
return "ALiPayment".equals(paymentMethod);
}
@Override
public void invokePay(Param param) {
System.out.println("使用支付宝进行支付");
}
}
@Service("WXPayment")
public class ALiPayment implements IPaymentStrategy {
@Override
public boolean accept(String paymentMethod) {
return "WXPayment".equals(paymentMethod);
}
@Override
public void invokePay() {
System.out.println("使用微信进行支付");
}
}
入口类1
@Component
public class userPayService {
@Autowired
private List<IPaymentStrategy> paymentStrategies;
public void pay(String paymentMethod){
IPaymentStrategy paymentStrategy = Optional.ofNullable(paymentStrategies).orElseGet(null)
.stream().filter(p -> p.accept(paymentMethod))
.findFirst().orElse(null);
if(paymentStrategy == null){
throw new RuntimeException("can not find paymentStrategy ");
}
paymentStrategy.invokePay();
}
}
入口类2
@Component
public class userPayService {
@Autowired
private Map<String, IPaymentStrategy> paymentStrategies;
public void pay(String paymentMethod){
IPaymentStrategy paymentStrategy = paymentStrategies.get(paymentMethod);
if(paymentStrategy == null){
throw new RuntimeException("can not find paymentStrategy ");
}
paymentStrategy.invokePay();
}
}
BY THE WAY:
也可使用自定义注解+反射的方式实现策略模式