Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Command Design Pattern

Tags:

java

arrays

I have created a shell(like command Prompt). I am taking user input and comparing the string in if condition to execute which ever command has been entered. Due to this, there are alot of if statements in my java code which is something not ideal. I am looking for a better way to implement this part of the code. Is it possible to store all my commands, and then iterate through the array to see which commands needs to be executed? Any good suggestions?

if (cmd[0].equals("pwd"))   {`
                command = new Pwd();
                invoker = new Invoker(command);
                invoker.action();
              } 
else if (cmd[0].equals("ls"))  {
              command = new Ls();
              invoker = new Invoker(command); 
              invoker.action(); //this executes the command
              }

...so on

like image 932
zyas Avatar asked Dec 06 '25 05:12

zyas


2 Answers

You could try a HashMap<String, Command>().

Map<String, Command> commandMap = new HashMap<String, Command>();
commandMap.put("pwd", new Pwd());
commandMap.put("ls", new Ls());

if(commandMap.containsKey(cmd[0])) {
    new Invoker(commandMap.get(cmd[0])).action();
}
like image 164
QBrute Avatar answered Dec 08 '25 17:12

QBrute


As an alternative to a map you can use an enum for a fixed set of commands. With Java 8 the code is fairly neat:

class enum Command {
    PWD("pwd", Context::pwd),
    LS("ls", Context::ls);

    private final String command;
    private final Runnable action;

    Command(String command, Runnable action) {
        this.command = command;
        this.action = action;
    }

    public static run(String command) {
        Arrays.stream(values())
            .filter(c -> c.commmand.equals(command))
            .findAny().ifPresent(c -> c.action.run());
    }
}
like image 39
sprinter Avatar answered Dec 08 '25 18:12

sprinter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!