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

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

问题描述

抱歉,我找不到可以回答这个问题的问题,我几乎可以肯定其他人之前已经提出过这个问题.

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 命令模式:

public interface Command {
     void exec();
}

public class CommandA() implements Command {

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

// etc etc

然后构建一个 Map 对象并用 Command 实例填充它:

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

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

然后你可以用:

commandMap.get(value).exec();

编辑

您还可以添加特殊命令,例如 UnknownCommandNullCommand,但是您需要一个 CommandMap 来处理这些极端情况以最小化客户的支票.

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天全站免登陆