首先我们要知道switch中需要执行什么方法,以及用到的参数,返回值之类的
之后创建一个接口,下面是我定义的接口
public interface GeneralImportService {
/**
* 方法
* @param o 入参
* @return 返回体
*/
UploadContext invoke(Object o);
}
之后使用map将接口实现
public class GeneralImport {
//UploadMethodNames为枚举,GeneralImportService为接口,既可以实现指定枚举运行指定接口
private Map<UploadMethodNames, GeneralImportService> map = new HashMap<>(16);
//这里获取一下baen,只是我当时要使用到这个baen
private static final ProjectUploadApiService projectUploadApiService = SpringContextUtil.getBean(ProjectUploadApiService.class);
private GeneralImport() {
}
//将已知的方法进行存入map,使用Lambda表达式实现接口
private static GeneralImport IF_GENERAL_IMPORT = new GeneralImport()
.add(UploadMethodNames.COMPANY_IMPORT, ( n) -> {
return projectUploadApiService.companyImport(companyImports);
})
.add(UploadMethodNames.LABOURER_IMPORT, ( n) -> {
return projectUploadApiService.labourerImport(labourerImports);
})
/**
* 提供⼀个公共的访问⽅式,需静态⽅法,以使类名直接调⽤,以达到外界能够访问
*/
public static GeneralImport getInstance() {
return IF_GENERAL_IMPORT;
}
/**
* 添加条件
*
* @param key 需要验证的条件(key)
* @param function 要执行的方法
* @return this.
*/
public GeneralImport add(UploadMethodNames key, GeneralImportService function) {
this.map.put(key, function);
return this;
}
/**
* 确定key是否存在,如果存在,则执行相应的方法。
*
* @param key the key need to verify
*/
public UploadContext doIf(UploadMethodNames key, Object o) {
if (this.map.containsKey(key)) {
return map.get(key).invoke( o);
}
//这里也可以设置默认执行方法
return UploadContext.failed("方法不存在");
}
}
获取baen
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
applicationContext = context;
}
/**
* 静态加载applicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 通过反射获取Bean
*
* @param requiredType
* @param <T>
* @return
*/
public static <T> T getBean(Class<T> requiredType) {
return getApplicationContext().getBean(requiredType);
}
/**
* 通过id名获取bean
*
* @param name
* @param <T>
* @return
*/
public static <T> T getBean(String name) {
return (T) getApplicationContext().getBean(name);
}
}
返回体
@Data
public class UploadContext implements Serializable {
private String message;
private String code;
private Object data;
private String token;
}
调用
UploadContext uploadContext = GeneralImport.getInstance().doIf(uploadMethodNames, o);