策略模式,简单来说就是代替if else…
实际项目中会多种设计模式混合使用,以达到目的。
策略实现类的向上接口:
/**
* 第三方通道service
* @author ethan
*/
public interface AccountMsgService {
/**
* 获取收款账户信息
* @return void
* @author ethan
* 2019年2月19日14:00:40
*/
public ReceiveBankAccount getAccount(Integer paycenterId,Integer projectId);
}
多个支付渠道的具体实现类:
以支付宝为例:
/**
* 阿里支付渠道
* @author ethan
* 2019年2月19日14:30:10
*/
@Service("aliPayChannel")
public class AliPayChannelImpl implements AccountMsgService {
/**
* 具体支付接口
* @author ethan
* 2019年2月19日14:46:46
*/
@Override
public ReceiveBankAccount getAccount(Integer paycenterId,Integer projectId) {
//具体的业务逻辑
return null;
}
调用方法:
public ReceiveBankAccount getReceiveBankAccount(Integer paycenterId,Integer projectId){
AccountMsgService accountMsgService = StragetyFactory.getInstance().getPayChannelService(paycenterId);
if(Objects.isNull(accountMsgService)){
throw new ErrorCodeException(ErrorCode.SYSTEM_ERROR);
}
return accountMsgService.getAccount(paycenterId,projectId);
}
策略工厂:
/**
* 获取收款账户信息 主或子账户
* @author ethan
* 2019年2月19日13:55:00
*/
public class StragetyFactory {
private static final StragetyFactory INSTANCE = new StragetyFactory();
private StragetyFactory (){}
public static final StragetyFactory getInstance() {
return INSTANCE;
}
/**
* 获取收款账户信息
* @author ethan
* 2019年2月19日13:54:42
*/
public AccountMsgService getPayChannelService(Integer channelId){
if(Objects.isNull(channelId)){
return null;
}
String beanName = PayChannelCenterDesc.getDesc(channelId.intValue()).server;
if(StringUtils.isBlank(beanName)){
return null;
}
//通过channelId 获取到对应的实现类
return (AccountMsgService)BusinessServerContext.getApplicationContext().getBean(beanName);
}
}
把service名称放到枚举里
/**
* 支付渠道
* @author ethan
* 2019年2月19日14:06:06
*/
public enum PayChannelDesc {
/**
* 微信
*/
微信支付(1001,"wxChannel"),
/**
* 支付宝支付
*/
支付宝(1002,"aliPayChannel"),
/**
* 京东支付
*/
京东(1003,"jdPayChannel");
public int centerId;
public String server;
private PayChannelDesc(int centerId, String server){
this.centerId = centerId;
this.server = server;
}
public static PayChannelDesc getDesc(int centerId){
return Arrays.stream(values()).filter(e -> Objects.equals(centerId,e.centerId)).findFirst().orElse(null);
}
public int getCenterId() {
return centerId;
}
}
spring上下文
/**
* 获取容器上下文
* @author ethan
* @date 2019年2月19日15:31:19
*/
@Component
public class BusinessServerContext implements ApplicationContextAware {
private static ApplicationContext context;
public static ApplicationContext getApplicationContext() {
return context;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
}
over!