最近项目中业务需要 根据不同事项名称执行相应的业务逻辑,代码中出现大量 if else 着实头疼,参考他人博文 代码做了修改,现在记录下来 巩固一下
优化前逻辑
public void get(){
if ("事项一".equals(ContantDemo.BUSINESS_TYPE_1)){
//执行事项一逻辑
}
if ("事项二".equals(ContantDemo.BUSINESS_TYPE_2)){
//执行事项2逻辑
}
if ("事项三".equals(ContantDemo.BUSINESS_TYPE_3)){
//执行事项3逻辑
}
if ("事项四".equals(ContantDemo.BUSINESS_TYPE_4)){
//执行事项4逻辑
}
if ("事项五".equals(ContantDemo.BUSINESS_TYPE_5)){
//执行事项5逻辑
}
//每新增一个事项就要多一套if
}
代码优化:
一.事项常量池
public interface ContantDemo {
String BUSINESS_TYPE_1 = "事项一";
String BUSINESS_TYPE_2 = "事项二";
String BUSINESS_TYPE_3 = "事项三";
String BUSINESS_TYPE_4 = "事项四";
String BUSINESS_TYPE_5 = "事项五";
}
二.定义接口,事项执行方法
public interface BusinessSerive {
/**
* 事项执行的方法 抽象
*/
void runBusiness();
}
三.定义每个事项具体实现类
/**
* 事项一具体实现类
*/
@BusinessType(ContantDemo.BUSINESS_TYPE_1)//自定义的注解,下面会有说明
public class BusinessServiceImpl implements BusinessSerive {
@Override
public void runBusiness() {
//事项一 出处理的业务逻辑
}
}
四.定义上下文实现类
public class BusinessContext {
//维护一个Map
private Map<String,BusinessSerive> map;
public BusinessContext() {
this.map = new HashMap<>();
}
public void putMap(String businessName,BusinessSerive businessClass) {
this.map.put(businessName,businessClass);
}
public BusinessSerive getForMap(String businessName) {
return this.map.get(businessName);
}
}
五.自定义注解
@Documented
@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface BusinessType {
String value();
}
六.定义监听器自动装配事项对应事项实现类
@Component
//注意ApplicationListener<ContextRefreshedEvent> 泛型定义 监听器监听时机
public class BusinessListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
// 监听器 装载 事项名称 事项实现 进事项上下文 map
Map<String,Object> beans = event.getApplicationContext().getBeansWithAnnotation(BusinessType.class);
BusinessContext context = event.getApplicationContext().getBean(BusinessContext .class);
beans.forEach((name,bean) -> {
BusinessType businessType= bean.getClass().getAnnotation(BusinessType.class);
context .putBusiness(businessType.value(),(BusinessService) bean);
});
}
}
7.具体使用
public void get(){
if ("事项一".equals(ContantDemo.BUSINESS_TYPE_1)){
//执行事项一逻辑
}
if ("事项二".equals(ContantDemo.BUSINESS_TYPE_2)){
//执行事项2逻辑
}
if ("事项三".equals(ContantDemo.BUSINESS_TYPE_3)){
//执行事项3逻辑
}
if ("事项四".equals(ContantDemo.BUSINESS_TYPE_4)){
//执行事项4逻辑
}
if ("事项五".equals(ContantDemo.BUSINESS_TYPE_5)){
//执行事项5逻辑
}
//代码重构后
BusinessSerive businessSerive = businessContext.getForMap(ContantDemo.BUSINESS_TYPE_1);
businessSerive.runBusiness();//执行事项逻辑
}