策略模式(支付案例)
最近在github上学习了几个开源项目,自己也认知到自己的不足,所有就想到 if else 这个判断语句。如果说类型很多,用switch,那么我增加一个类型,是不是又要在原来的基础上改代码,这违反了“开闭原则”,所有才有了今天的文章案例。
enum
支付抽象层
@Service
public interface paymentService {
/** 支付*/
String payment();
/** 获取支付类型*/
Payment getType();
}
支付宝支付实现
@Service
public class ZfbPaymentServiceImpl implements paymentService {
@Override
public String payment() {
return "支付宝支付";
}
@Override
public Payment getType() {
return Payment.ZFB;
}
}
支付抽象工厂
public interface ConText {
paymentService paymentServiceSelect(int type);
}
支付抽象工厂实现
@Service
public class PaymentConText implements ConText {
@Autowired
private List<paymentService> paymentService;
@Override
public paymentService paymentServiceSelect(int type) {
List<paymentService> paymentServiceLIst = paymentService.stream().filter(x->x.getType().getCode() == type).collect(Collectors.toList());
return paymentServiceLIst.get(0);
}
}
支付控制层
@RestController
@RequestMapping("/pay")
public class PlayController {
@Autowired
private ConText conText;
@GetMapping("/payment")
public String payment(int type){
return conText.paymentServiceSelect(type).payment();
}
}
