1、添加@Component,交给spring管理
2、实现ApplicationContextAware
3、setApplicationContext获取所有实现类,注入到map中
@Component
public class StrategyContext implements ApplicationContextAware
{
Map<String, ISignatureStrategy > map = new HashMap<>();
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
map = applicationContext.getBeansOfType(ISignatureStrategy .class);
}
//获取策略实例
public ISignatureStrategy getPayStrategy(String platform) {
return map.get(platform + "SignatureStrategy");
}
}
注意:
applicationContext.getBeansOfType(IStrategy.class) 获取IStrategy所有实现类,之后添加新的实现类,不需要做额外的代码增加
4、策略类定义
public interface ISignatureStrategy {
# 设置成 default 方法,子类可有选择的实现方法
default String getPersonAuth() {
return "父类第一个方法";
}
# 入参、出参设置成Object,子类可按需设置参数
default Object getPersonAuthResp(Object o) {
return null;
}
}
5、适配器定义
@Component
public class EqianbaoSignatureAdapter {
/**
* 获取个人认证dto
* @return
*/
@Bean
public EPersonAuthDTO getPersonAuth(PersonAuthVO personAuthVO) {
EPersonAuthDTO ePersonAuthDTO = new EPersonAuthDTO();
ePersonAuthDTO.setEName(personAuthVO.getName());
return ePersonAuthDTO;
}
}
6、策略类实现
@Component
public class EqianbaoSignatureStrategy implements ISignatureStrategy {
private final EqianbaoSignatureAdapter eqianbaoSignatureAdapter = new EqianbaoSignatureAdapter();
@Override
public String getPersonAuth() {
return "获取个人认证";
}
# 入参需要将Object向下转型,出参可直接输出
@Override
public Object getPersonAuthResp(Object object) {
PersonAuthVO personAuthVO = (PersonAuthVO) object;
return eqianbaoSignatureAdapter.getPersonAuth(personAuthVO);
}
}
7、控制层进行调用
private final StrategyContext strategyContext;
@Override
public Object getPersonAuthResp(PersonAuthVO personAuthVO) {
ISignatureStrategy payStrategy = strategyContext.getPayStrategy(personAuthVO.getPlatform());
return payStrategy.getPersonAuthResp(personAuthVO);
}