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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…