策略模式
设计模式,若使用得当,将会使我们的代码更简洁,并且更具扩展性。下面以支付为例
- 依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
- 抽象一个支付接口
// 支付接口
public interface IPay {
// 是否支持
boolean support(Integer type);
// 支付
void pay(WorkOrder workOrder);
}
- 支付方式实现该接口
- 支付宝
@Component
public class AliPay implements IPay{
public boolean support(Integer type) {
return type == PayType.UNIONPAY.getValue();
}
public void pay(WorkOrder workOrder) {
// 调用支付宝相关方法
System.out.println("支付宝支付成功");
}
}
- 微信支付
@Component
public class WechatPay implements IPay{
public boolean support(Integer type) {
return type == PayType.UNIONPAY.getValue();
}
public void pay(WorkOrder workOrder) {
//
System.out.println("微信支付成功");
}
}
- 银行卡支付
@Component
public class UnionPay implements IPay{
public boolean support(Integer type) {
return type == PayType.UNIONPAY.getValue();
}
public void pay(WorkOrder workOrder) {
// 银行卡支付
System.out.println("银行卡支付成功");
}
}
工厂模式
@Component
public class PayFactory {
@Autowired
private List<IPay> pays;
public IPay getPay(Integer type){
for (IPay pay : pays) {
if(pay.support(type)){
return pay;
}
}
throw new UnsupportedOperationException("Unsupported Pay");
}
public class WorkOrder {
private String id;
private String userId;
private Double price;
private int payType;
// ... get、set省略
}
public enum PayType {
ALIPAY(1),
WECHATPAY(2),
UNIONPAY(3);
private final int value;
PayType(int value){
this.value = value;
}
public int getValue() {
return value;
}
}
@Service
public class PayService {
@Autowired
private PayFactory factory;
public void pay(WorkOrder workOrder){
factory.getPay(workOrder.getPayType()).pay(workOrder);
}
}
@Configuration
@ComponentScan("com.qooence.code.service")
public class Config {
}
测试
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
PayService payService = context.getBean(PayService.class);
WorkOrder workOrder = new WorkOrder();
workOrder.setId("wo_2019_08_29_15_40_123");
workOrder.setPrice(256.0);
workOrder.setUserId("123");
workOrder.setPayType(PayType.ALIPAY.getValue());
payService.pay(workOrder);
}