问题描述:
在你的代码中是否会出现这种情况,用很多的if else语句来执行对应的功能模块,并且各个分支模块中共同的部分也还不少,当后续迭代量上来后,随之而来的模块分支可能也会增多,有什么方法可以消除分支吗?
public String sayHello(String type) {
//不同的类型有不能的业务处理,导致if else太多太多。宝宝心里苦啊..........................................
if ("rice".equals(type)){
return "你好,大米";
}else if ("wheat".equals(type)){
return "你好,小麦";
}else {
return "我不认识你";
}
}
解决方案:
大家都是程序员,直接上代码吧。
@Component
public class StrategySelector {
private Map serviceMap;
//Spring会把所有StrategyService的实现类放到services这个变量中
@Autowired
public void setServices(List services) {
//java stream转换成map
serviceMap = services.stream().collect(Collectors.toMap(StrategyService::getType, Function.identity(), (k1, k2) -> k2));
}
public StrategyService getService(String type) {
return serviceMap.get(type);
}
}
public interface StrategyService {
String sayHello(String type);
String getType();
}
@Service
public class WheatStrategyServiceImpl implements StrategyService {
@Override
public String sayHello(String type) {
return "你好,小麦";
}
@Override
public String getType() {
return "wheat";
}
}
@Service
public class RiceStrategyServiceImpl implements StrategyService {
@Override
public String sayHello(String type) {
return "你好,大米";
}
@Override
public String getType() {
return "rice";
}
}
@Service
public class OtherStrategyServiceImpl implements StrategyService {
@Override
public String sayHello(String type) {
return "我不认识你";
}
@Override
public String getType() {
return "other";
}
}
@RestController
@RequestMapping("/strategy")
public class StrategyController {
@Resource
private StrategySelector selector;
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String process2(String type) {
StrategyService service = selector.getService(type);
return service.sayHello(type);
}
}
完整代码参考:https://github.com/465919283/demo