Java中的if语句的长列表 [英] Long list of if statements in Java

查看:247
本文介绍了Java中的if语句的长列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,我找不到一个回答这个问题的问题,我几乎可以肯定别人提出了这个问题。



我的问题是我正在编写一些系统库来运行嵌入式设备。我有可以通过无线电广播发送到这些设备的命令。这只能通过文本来完成。在系统库里面我有一个线程来处理看起来像这样的命令

  if(value.equals(A) ){doCommandA()} 
else if(value.equals(B)){doCommandB()}
else if等

问题是有很多命令会很快地扭曲到一些失控的东西。可怕的看着,痛苦的调试和头脑令人难以置信的理解在几个月的时间。

解决方案

使用命令模式

  public interface Command {
void exec();
}

public class CommandA()实现Command {

void exec(){
// ...
}
}

// etc etc

然后构建一个 Map< String,Command> 对象,并使用命令实例:

  commandMap.put(A,新的CommandA()); 
commandMap.put(B,new CommandB());

然后,如果 / else if chain with:

  commandMap.get(value).exec(); 

编辑



<您也可以添加特殊命令,例如 UnknownCommand NullCommand ,但是您需要一个 CommandMap 可以处理这些角色,以最大程度地减少客户端的检查。


Sorry I can't find a question answering this, I'm almost certain someone else has raised it before.

My problem is that I'm writing some system libraries to run embedded devices. I have commands which can be sent to these devices over radio broadcasts. This can only be done by text. inside the system libraries I have a thread which handles the commands which looks like this

if (value.equals("A")) { doCommandA() }
else if (value.equals("B")) { doCommandB() } 
else if etc. 

The problem is that there are a lot of commands to it will quickly spiral to something out of control. Horrible to look out, painful to debug and mind boggling to understand in a few months time.

解决方案

using Command pattern:

public interface Command {
     void exec();
}

public class CommandA() implements Command {

     void exec() {
          // ... 
     }
}

// etc etc

then build a Map<String,Command> object and populate it with Command instances:

commandMap.put("A", new CommandA());
commandMap.put("B", new CommandB());

then you can replace your if/else if chain with:

commandMap.get(value).exec();

EDIT

you can also add special commands such as UnknownCommand or NullCommand, but you need a CommandMap that handles these corner cases in order to minimize client's checks.

这篇关于Java中的if语句的长列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆