How to simplify this logic / code?

I want to write applications that accept a user command. The user command is used in this format:

command -parameter

For example, the application may have the command "Copy", "Paste", "Delete". I think that the program should work as follows:

public static void main(String args[]){

   if(args[0].equalsIgnoreCase("COPY")){
     //handle the copy command

   } else if(args[0].equalsIgnoreCase("PASTE")){
     //handle the copy command


   }/**
    code skipped
     **/


}

So it works, but I think it will become more and more complex when I have more teams in my program, also, this is not the case to read. Any ideas just logic?

+5
source share
5 answers

, Commons CLI .
> CommandLineParser

if-else, Command Pattern

public interface Command {
     void exec();
}

public class Copy implements Command {    
     void exec() {
          // your copy Code 
     }
}

public class Paste implements Command {    
     void exec() {
          // your Paste Code 
     }
}


public class Delete implements Command {    
     void exec() {
          // your Delete Code 
 }

-

public static void main(String args[]){
Map commandMap<String,Command> = new HashMap<String,Command>();
commandMap.put("Copy", new Copy());
commandMap.put("Paste", new Paste());
commandMap.put("Delete", new Delete());

if ( commandMap.containsKey(args[0]) ){
commandMap.get(args[0]).exec();

}
}
+7

, , enum

public enum Command {
    COPY {
        @Override void execute() {
            System.out.println("Copying...");
        }
    },
    PASTE {
        @Override void execute() {
            System.out.println("Pasting...");
        }       
    },
    DELETE  {
        @Override void execute() {
            System.out.println("Deleting...");          
        }
    },
    ;

    abstract void execute();

    public static void main(String args[]) {
        Command c = Command.valueOf(args[0].toUpperCase());
        c.execute();
    }
}

java Command paste, java Command bleh .. args . , valueOf throws IllegalArgumentException, enum .


, , , . Apache Commons CLI.

+7

, , args4j.

+3

if/then/else, .

- . Java, :

public interface Command<T, V>
{
    V execute(T parameter) throws Exception;
}

, Runnable , Callable <T> , .

if/then/else Map, , Command. , . , Command Map. - , . , (/ ).

+1

, , .

0

All Articles