switch-statement - 是否有 switch 语句的替代方法,我将如何组织它?
问题描述
编码一段时间后,我突然想到 switch 语句可能不是运行我的代码的最佳函数,例如,我不能将 case 语句简化为它们自己的方法,因为它们将是孤立的 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;
我预计这会比结果要简化得多,但我似乎无法将案例陈述分解成他们自己的方法,所以一切都更有条理。
解决方案
在这种情况下,我的方法是编写工厂模式和命令模式。要完成的每个“部分”工作都可以放在一个类中,该类使用一个重要方法实现接口: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();
}
这样你就可以无休止地创建不同的命令,直到“退出”命令简单地关闭游戏......例如带有一条消息。
开关只是移动到工厂,但即使在那里,您也可以增强工厂以通过反射从配置文件中读取类名并将它们放置在字符串到命令对象的映射中(映射键将是一个字符串,即命令键。并且Map 值将是 Command 对象)。所以你将从你的程序中完全删除 switch 的使用。
推荐阅读
- java - Spring Scheduler 失败
- php - 在php中将整数转换为十进制值
- python-3.6 - Wsgi 错误:ModuleNotFoundError:没有名为“django_webapp”的模块
- node.js - Express 服务器在 EC2 上没有响应
- html - 在 CSS 中调整滚动球的高度
- python - 谁能解释一下这个代码中successful_frame_read的目的是什么?
- node.js - 使用 icognito 身份池时,在 Lambda 函数中获取 context.identity 中的用户信息
- javascript - 如何在 React 中从多个端点获取和显示数据?
- django - 从 rest-auth social Login 获取用户 ID
- c# - 每当我通过 SSH-ing 执行我的 git 命令时,我在 c# 代码输出中遇到错误