场景:最近在写一些接口,发现堆了太多的if…eles,所以通过实现Spring框架的InitializingBean接口,加上策略模式,避免代码里堆了太多if…else
实现思路:
大量的if…else堆积:
if (condition1 || condition2) {
// 具体实现业务
} else if ( condition3 || condition4) {
// 具体业务
} else if (condition5 || condition6) {
// ...
}
...
策略类接口
public interface InfoStrategy {
List<InfoModel> obtainInfo(InfoQeury qeury);
String getType();
}
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumMap;
import java.util.List;
@Service
@Slf4j
public class InfoServiceImpl implements InfoService, ApplicationContextAware, InitializingBean {
private List<LInfoStrategy> queryStrategys = new ArrayList<>();
private ApplicationContext applicationContext;
@Override
public List<InfoModel> listInfo(InfoQeury query) {
String type = query.getType();
log.info("传参 Type : {} , Code : {}" , type , code);
return getStrategy(type).obtainInfo(query);
}
@Component
class Strategy1 implements InfoStrategy {
@Override
public List<InfoModel> obtainInfo(InfoQeury qeury) {
// ...
return infos;
}
@Override
public String getType() {
return FlagType.1_FLAG.getCode();
}
}
@Component
class Strategy2 implements InfoStrategy {
@Override
public List<InfoModel> obtainInfo(InfoQeury qeury) {
// ...
return infos;
}
@Override
public String getType() {
return FlagType.2_FLAG.getCode();
}
}
@Component
class Strategy3 implements InfoStrategy {
@Override
public List<InfoModel> obtainInfo(InfoQeury qeury) {
// ...
return infos;
}
@Override
public String getType() {
return FlagType.3_FLAG.getCode();
}
}
private InfoStrategy getStrategy(String strategyName) {
for (InfoStrategy strategy : queryStrategys) {
if (strategy.getType().equals(strategyName)) {
return strategy;
}
}
return null;
}
@Override
public void afterPropertiesSet() throws Exception {
Collection<InfoStrategy> strategys =
applicationContext.getBeansOfType(InfoStrategy.class).values();
queryStrategys.addAll(strategys);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://smilenicky.blog.csdn.net/article/details/121875562
内容来源于网络,如有侵权,请联系作者删除!