Есть ли альтернатива инструкции switch, и как бы я это организовал? - PullRequest
0 голосов
/ 21 мая 2019

После того, как я некоторое время писал код, мне пришло в голову, что оператор switch может быть не самой лучшей функцией для запуска моего кода, например, я не могу упростить операторы case до собственных методов, потому что они будут осиротевшими. Мне было интересно, есть ли способ упростить этот код и каким образом я мог бы сделать это.

Я попытался написать несколько утверждений if, которые приводят к еще большему хаосу и беспорядку, хотя я мог бы все использовать по-своему. Это привело меня к утверждению switch, однако я не мог упростить это.

вот сегмент кода. Это включает в себя всеобъемлющий оператор switch и первый случай.

while (true) // игровой цикл {

        if (user.equalsIgnoreCase("exit")) { //if player types exit at any time the game quits
            System.exit(0);
        } else { //else the game runs

            map();
            Commands(); //runs the command method
            playerDam(); //runs player damage method

            //Handles the story
            switch (question) //if question is equal to...
            {
                case "1": //introduction
                    System.out.println("Welcome to Archewind" +
                        "\nIf in need of help, press help at any time for list of commands. \nIf you would like to exit type exit at any time." +
                        "\nAre you ready to begin? \n[1]Yes\n[2]No");
                    switch (user = in .next()) //if user types one... if two...
                    {
                        case "1": //this happens
                            System.out.println("\n");
                            System.out.println("Great. Good luck");

                            question = "1.5";
                            gametic = 1;
                            break;

                        case "2": //this happens
                            System.out.println("\n");
                            System.out.println("Oh... well um... I don't really know what to do here. People usually say yes.");
                            System.out.println("\nDo you think you're ready now? \n[1]Yes \n[2]No");

                            switch (user = in .next()) {
                                case "1":
                                    System.out.println("\n");
                                    System.out.println("Ok goood, I was getting worried there for a second. Good luck.");

                                    question = "1.5";
                                    gametic = 1;
                                    break;

                                case "2":
                                    System.out.println("\n");
                                    System.out.println("Really? [1]Yes [2]No");

                                    switch (user = in .next()) {
                                        case "1":
                                            System.out.println("\n");
                                            System.out.println("This is just getting long. Do you know what you're doing to the programmer? He has to code all of this you know" +
                                                "\nIm just going to give you a choice. Either say yes next time or I am going to shut down. I mean it." +
                                                "\nStart game? \n[1]Yes \n[2]No");

                                            switch (user = in .next()) {
                                                case "1":
                                                    System.out.println("\n");
                                                    System.out.println("Alllrriiight.. Lets get this party started.");
                                                    question = "1.5";
                                                    gametic = 1;
                                                    break;


                                                case "2":
                                                    System.out.println("\n");
                                                    System.out.println("Nope. I'm done.");
                                                    user = "exit";
                                                    break;
                                            }
                                            case "2":
                                                System.out.println("Ok good. We can finally get this show on the road.");
                                    }
                            }
                            question = "1.5";
                            gametic = 1;
                            break;
                    }
                    break;

Вот еще один сегмент.

кейс "1.5":

                    System.out.println("\nNow, before we start you need to choose a class. Each one will offer diffrent benefits.");
                    int rank = getRank();
                    userClass = RANKS[rank];
                    System.out.println("Your chosen class is: " + userClass);

                    if (userClass.equals("Farmer")) {
                        playerhealth = playerhealth + 1;
                        inv.remove("Health Potion");
                        inv.remove("Water Bottle");
                    }

                    if (userClass.equals("Trader")); {
                        inv.add("Health Potion");
                        inv.remove("Water Bottle");
                        if (playerhealth == 6) {
                            playerhealth = playerhealth - 1;
                        }
                    }

                    if (userClass.equals("Wanderer")); {
                        inv.add("Water Bottle");
                        inv.remove("Health Potion");
                        if (playerhealth == 6) {
                            playerhealth = playerhealth - 1;
                        }
                    }

                    gametic = 2;
                    question = "2";
                    break;

Я ожидал, что это будет намного проще, чем оказалось, но, похоже, я не могу разбить операторы case на их собственные методы, чтобы все было гораздо более организованным.

1 Ответ

0 голосов
/ 21 мая 2019

Мой подход в этом случае - написать шаблон Factory вместе с шаблоном Command. Каждый «сегмент» выполняемой работы может быть помещен в класс, который реализует интерфейс с одним важным методом: execute (). Следующее: Интерфейс:

public interface Command {
    void execute();
}

Все команды будут реализовывать это:

public class SayWelcomeCommand implements Command {
    @Override
    public void execute() {
        System.out.println("Welcome");
    }
}

И еще одна команда для работы «Трейдера»:

public class TraderCommand implements Command {
    @Override
    public void execute() {
        // doing some work...
        inv.add("Health Potion");
        inv.remove("Water Bottle");
        // more work...      
    }
}

Вы создаете команды в соответствии с известным строковым ключом:

public class CommandsFactory {
    public static Command createCommand(String commandKey) {
        switch (commandKey) {
        case 'welcome': return new SayWelcomeCommand(); break;
        case 'trader': return new TraderCommand(); break;
        case 'exit': return new ExitCommand(); break;  // todo: create that cmd..
        }
    }
}

Теперь в вашей MAIN-программе вы просто вызываете фабрику и выполняете!

while (true) {
    String commandKey =  System.in.readLine... // get from the user a command.
    Command command = CommandFactory.createCommand(commandKey);
    command.execute();
}

Таким образом, вы продолжаете бесконечно создавать различные команды, пока команда «выход» не просто выключит игру ... с сообщением, например.

Переключатель просто переместился на Фабрику, но даже там вы можете улучшить фабрику, чтобы прочитать путем отражения имен классов из конфигурационного файла и поместить их в карту объектов String to Command (ключ Map будет строкой, команда и значение Map будет объектом Command). так что вы полностью удалите использование switch из вашей программы.

...