温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java中if-else过多怎么解决

发布时间:2020-11-11 14:35:36 来源:亿速云 阅读:316 作者:Leah 栏目:开发技术

Java中if-else过多怎么解决?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

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

String input = "three";

  @Test
  public void testElse() {
    if ("one".equals(input)) {
      System.out.println("one");
    } else if ("two".equals(input)) {
      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<Handler> 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<ReflectTest, Object> invokable =
        (Invokable<ReflectTest, Object>) Invokable.from(method);
    invokable.invoke(new ReflectTest());
  } 

3. lambda表达式

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

  @Test
  public void testJava8() {
    Map<String, Consumer<ReflectTest>> 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();
  }

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI