Ich habe diesen Code, der meine Befehle behandelt:Ist es in Ordnung, so viel NEUE Anweisung zu verwenden?
public class CommandHandler {
public static final CommandParser parser = new CommandParser();
public static HashMap<String, Command> commands = new HashMap<>();
public static void handleCommand(CommandParser.CommandContainer cmd) {
if (commands.containsKey(cmd.invoke)) {
commands.get(cmd.invoke).action(cmd.event, cmd.args);
commands.get(cmd.invoke).postAction(cmd.event, cmd.args);
}
/* else
System.err.println("CMD NOT EXIST!"); */
}
}
public static HashMap<String, Command> commands = new HashMap<>();
private static void addCommands() {
commands.put(new cmdConfig().getCommand(), new cmdConfig());
commands.put(new cmdHelp().getCommand(), new cmdHelp());
commands.put(new cmdPing().getCommand(), new cmdPing());
}
Dies ist ein kurzer Code, aber ich habe 157 Befehle. Jeder Befehl erstreckt sich von einer Schnittstelle, die diese Methoden haben:
public interface Command {
public String getCommand();
public String help();
public void action(String[] args);
public void postAction(String[] args);
}
Auch
, verwende ich diesen Code zu:
String input = "random";
if (new cmdPing().getCommand().equals(input)) {
new cmdPing().help();
}
else if (new cmdConfig().getCommand().equals(input)) {
new cmdConfig().help();
}
else {
printError(input + " is not a valid command");
}
und ich möchte wissen, ob in Ordnung ist, zu viele neue Aussagen zu verwenden, wenn i Verwenden Sie commands.put
und innerhalb von if()
Aussagen auch.
Was ist sonst in den Befehlsklassen abgesehen von den Strings, die von den beiden Accessor-Methoden zurückgegeben werden, und dem (ich nehme an) gemeinsamen Impl von 'action()'? – Bohemian
Sieht aus, als wäre dein Design kaputt. 'put (new cmdConfig(). getCommand(), new cmdConfig())' sollte mindestens so geschrieben werden wie 'c = new cmdConfig(); put (c.getCommand(), c) '. Sieht so aus, als ob Sie viele Objekte erstellen, nur um eine konstante Zeichenkette zu erhalten, erstellen Sie ein letztes statisches Feld in der Klasse ... –
Danke für die Hilfe! – INeedHelpWithTheCode