Java中避免过多if-else的几种方法
太多的if-else不太直观,难以维护。
以下面代码为例,展示几种替代ifelse的方法。
Stringinput="three";
@Test
publicvoidtestElse(){
if("one".equals(input)){
System.out.println("one");
}elseif("two".equals(input)){
System.out.println("two");
}elseif("three".equals(input)){
System.out.println("three");
}elseif("four".equals(input)){
System.out.println("four");
}
}
需要引入Spring跟Guava依赖
1.Spring结合策略模式
Spring可以将一组实现了同样接口的类注入一个List
/***
*定义接口。type用来路由具体的Handler实现
**/
publicinterfaceHandler{
StringgetType();
voidexecute();
}
/**
*将Handler接口的实现类注入一个List
**/
@Autowired
privateListhandlerList;
@Test
publicvoidtestAutowireList(){
//根据类型判断该由哪个具体实现类处理
for(Handlerhandler:handlerList){
if(input.equals(handler.getType())){
handler.execute();
}
}
}
下面是几种轻量级实现.
2.反射
通过反射动态调用相应的方法
/***
*定义每种类型所对应的方法
*/
publicclassReflectTest{
publicvoidmethodOne(){
System.out.println("one");
}
publicvoidmethodTwo(){
System.out.println("two");
}
publicvoidmethodThree(){
System.out.println("three");
}
publicvoidmethodFour(){
System.out.println("four");
}
}
/***
*
*通过反射,动态调用方法。采用了Guava的工具类。
**/
@Test
publicvoidtestReflect()throwsException{
//首字母大写,根据类型拼接方法
StringmethodName="method"+LOWER_CAMEL.to(UPPER_CAMEL,input);
Methodmethod=ReflectTest.class.getDeclaredMethod(methodName);
Invokableinvokable=
(Invokable)Invokable.from(method);
invokable.invoke(newReflectTest());
}
3.lambda表达式
实现同上面的反射,结合了Java8的新特性:lambda表达式
@Test
publicvoidtestJava8(){
Map>functionMap=Maps.newHashMap();
functionMap.put("one",ReflectTest::methodOne);
functionMap.put("two",ReflectTest::methodTwo);
functionMap.put("three",ReflectTest::methodThree);
functionMap.put("four",ReflectTest::methodThree);
functionMap.get(input).accept(newReflectTest());
}
4.枚举
在枚举里面定义一个抽象方法,每种类型对应各自的具体实现。
/**
*定义枚举类,包含了所有类型
*/
publicenumEnumTest{
ONE("one"){
@Override
publicvoidapply(){
System.out.println("one");
}
},
TWO("two"){
@Override
publicvoidapply(){
System.out.println("two");
}
},THREE("three"){
@Override
publicvoidapply(){
System.out.println("three");
}
},FOUR("four"){
@Override
publicvoidapply(){
System.out.println("four");
}
};
publicabstractvoidapply();
privateStringtype;
EnumTest(Stringtype){
this.type=type;
}
publicStringgetType(){
returntype;
}
}
//枚举测试
@Test
publicvoidtestEnum(){
EnumTest.valueOf(input.toUpperCase()).apply();
}
到此这篇关于Java中避免过多if-else的几种方法的文章就介绍到这了,更多相关Java过多if-else内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!