Java中避免过多if

网友投稿 216 2023-02-25

Java中避免过多if

太多的if-else不太直观,难以维护。

以下面代码为例,展示几种替代if elsxyjiXe的方法。

String input = "three";

@Test

public void testElse() {

if ("one".equals(input)) {

System.out.println("one");

} else if ("two".equals(input)) {

http:// System.out.println("two");

} else if ("three".equals(input)) {

System.out.println("three");

} else if ("four".equals(input)) {

System.out.println("four");

}

}

需要引入Spring跟Guava依赖

1.Spring结合策略模式

Spring可以将一组实现了同样接口的类注入一个List

/***

* 定义接口。type用来路由具体的Handler实现

* */

public interface Handler {

String getType();

void execute();

}

/**

* 将Handler接口的实现类注入一个List

* */

@Autowired

private List handlerList;

@Test

public void testAutowireList(){

// 根据类型判断该由哪个具体实现类处理

for(Handler handler:handlerList){

if(input.equals(handler.getType())){

handler.execute();

}

}

}

下面是几种轻量级实现.

2. 反射

通过反射动态调用相应的方法

/***

*定义每种类型所对应的方法

*/

public class ReflectTest {

public void methodOne() {

System.out.println("one");

}

public void methodTwo() {

System.out.println("two");

}

public void methodThree() {

System.out.println("three");

}

public void methodFour() {

System.out.println("four");

}

}

/***

*

* 通过反射,动态调用方法。采用了Guava的工具类。

* */

@Test

public void testReflect() throws Exception {

//首字母大写,根据类型拼接方法

String methodName = "method" + LOWER_CAMEL.to(UPPER_CAMEL, input);

Method method = ReflectTest.class.getDeclaredMethod(methodName);

Invokable invokable =

(Invokable) Invokable.from(method);

invokable.invoke(new ReflectTest());

}

3. lambda表达式

实现同上面的反射,结合了java 8的新特性:lambda表达式

@Test

public void testJava8() {

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(new ReflectTest());

}

4. 枚举

在枚举里面定义一个抽象方法,每种类型对应各自的具体实现。

/**

* 定义枚举类,包含了所有类型

*/

public enum EnumTest {

ONE("one") {

@Override

public void apply() {

System.out.println("one");

}

},

TWO("two") {

@Override

public void apply() {

System.out.println("two");

}

}, THREE("three") {

@Override

public void apply() {

System.out.println("three");

}

}, FOUR("four") {

@Override

public void apply() {

System.out.println("four");

}

};

public abstract void apply();

private String type;

EnumTest(String type) {

this.type = type;

}

public String getType() {

return type;

}

}

// 枚举测试

@Test

public void testEnum() {

EnumTest.valueOf(input.toUpperCase()).apply();

}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:详解MyBatis日志如何做到兼容所有常用的日志框架
下一篇:在线大数据分析平台(大数据查询分析网)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~