Java中的if语句的长列表 [英] Long list of if statements in Java
问题描述
我的问题是我正在编写一些系统库来运行嵌入式设备。我有可以通过无线电广播发送到这些设备的命令。这只能通过文本来完成。在系统库里面我有一个线程来处理看起来像这样的命令
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屋!