How to replace switch-case to OOP

soh*_*hhe 1 java oop

I have methods with which I get data from a database. Depending on the variable that the user entered through the console, I must execute the desired method

       while (flag) {
           try {
               sw = new ScannerWrapper();
               menuHeader();
               int choice = sw.readInt();
               switch (choice) {
                   case 1:
                       System.out.println("Input first name: ");
                       String name = sw.readLine().toUpperCase();
                       printResults(DataParser.getFilmByName(name));
                       break;
                     case 0:
                       System.out.println("Bye-bye. Come again");
                       flag = false;
                       break;
                   default:
                       System.out.println("Please enter correct number");
               }
           } catch (Exception e) {
               System.out.println("Enter correct data");
           } finally {
               DBConnector.getInstance().closeConnection();
           }
       }
Run Code Online (Sandbox Code Playgroud)

This code is very bad.There are more than 5 cases with methods and the code becomes redundant

Vin*_*rat 6

You should have a look at the Strategy design pattern. That will allow you to abstract the logic related to an action.

On top of that, you want to replace the switch to find the right strategy according to the input variable. That is the job of the Factory design pattern, which in your case would return one of the different strategies according to the database value.

Basically:

interface UserAction { 
    public void execute();
}

class ListMovies implements UserAction { 
    public void execute() {
        // List the movies
    }
}

class ExitProgram implements UserAction { 
    public void execute() {
        // Kill kenny
    }
}

class Noop implements UserAction { 
    public void execute() {
        // Do nothing
    }
}
Run Code Online (Sandbox Code Playgroud)

And a factory:

class UserActionFactory {
    public UserAction make(int actionId) {
        switch (actionId) {
            0: return new ListMovies();
            1: return new ExitProgram();
            default: return new Noop();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Which then allows:

UserActionFactory factory = new UserActionFactory();
ScannerWrapper sw = new ScannerWrapper();

while (true) {
    menuHeader();
    int choice = sw.readInt();
    UserAction action = factory.make(choice);
    action.execute();
Run Code Online (Sandbox Code Playgroud)

}

This could also be the Command design pattern, depends on how you name things and instantiate objects for the rest of the classes.

  • 现在,如果你添加一个`Map<Integer,UserAction>`,你实际上可以回答OP的问题“*如何将switch-case*替换为OOP”...... (3认同)