动态切换案例,将方法作为映射值 – Java

huangapple go评论100阅读模式
英文:

Dynamic switch case with Methods as Map Value - Java

问题

所以我的小项目有一个Scanner和两个重要的方法:

  1. 显示我可以在我的Scanner中输入的命令(运行其他方法)
  2. 一个带有命令的switch-case

以下是代码:

static void showCommands(){
    System.out.println("You can enter the following commands: "
            + "\nCommands: Lists your commands."
            + "\nInventory: Opens up your inventory"
            + "\nEquipment: Let's you equip your items"
            + "\nSpawnItem: Spawns a random item in your inventory"
            + "\nTravel: Travels your character"
            + "\nLocate: Locates your character"
            + "\nClose: Exits the game");
}

static void useCommands() {
    String input = "";
    Scanner sc = new Scanner(System.in);
    while (!input.equals("Close")) {
        input = sc.next();
        switch (input) {
        case "commands":
            showCommands();
            break;
        case "combatlevel":
            CombatLevel.showCombatLevel();
            break;
        case "totatlevel":
            TotalLevel.showTotalLevel();
            break;
        case "inventory":
            Inventory.showInventory();
            break;
        case "equipment":
            Equipment.showEquipment();
            break;
        case "equip":
            break;
        case "spawnitem":
            Item.spawnItem();
            break;
        case "travel":
            Map.travel();
            break;
        case "increaselevel":
            Player.getInstance().combatLevel.increaseCombatLevel();
            break;
        case "locate":
            Map.locate();
            break;
        case "close":
            sc.close();
            System.exit(0);
            break;
        }
    }
}

问题是:这个架构过于静态,因为我总是需要相应地更新两个方法以适应每个新命令,而且它本身感觉不够高效。

所以我想问一下是否可能使用一个Map,其中键是用户输入的Scanner字符串,值是Map的值动态启动方法。

像这样:

HashMap<String, Method> test = new HashMap<>();
test.put("test", test());

我尝试过这样做,但没成功,因为我的test()方法必须返回另一个方法,这对我来说没有意义。

有人有什么建议来解决这个问题吗?

祝好!

英文:

so my little project has a Scanner and two important methods:

  1. That shows the commands i can type in my scanner (runs other methods)
  2. A switch-case with the commands

And the following code:

static void showCommands(){
System.out.println(&quot;You can enter the following commands: &quot;
+ &quot;\nCommands: Lists your commands. &quot;
+ &quot;\nInventory: Opens up your inventory&quot;
+ &quot;\nEquipment: Let&#39;s you equip your items&quot;
+ &quot;\nSpawnItem: Spawns a random item in your inventory&quot;
+ &quot;\nTravel: Travels your character&quot;
+ &quot;\nLocate: Locates your character&quot;
+ &quot;\nClose: Exits the game&quot;);
}
static void useCommands() {
String input = &quot;&quot;;
Scanner sc = new Scanner(System.in);
while (!input.equals(&quot;Close&quot;)) {
input = sc.next();
switch (input) {
case &quot;commands&quot;:
showCommands();
break;
case &quot;combatlevel&quot;:
CombatLevel.showCombatLevel();
break;
case &quot;totatlevel&quot;:
TotalLevel.showTotalLevel();
break;
case &quot;inventory&quot;:
Inventory.showInventory();
break;
case &quot;equipment&quot;:
Equipment.showEquipment();
break;
case &quot;equip&quot;:
break;
case &quot;spawnitem&quot;:
Item.spawnItem();
break;
case &quot;travel&quot;:
Map.travel();
break;
case &quot;increaselevel&quot;:
Player.getInstance().combatLevel.increaseCombatLevel();
break;
case &quot;locate&quot;:
Map.locate();
break;
case &quot;close&quot;:
sc.close();
System.exit(0);
break;
}
}
}

The problem is: the architecture is too static, since I always need to update both methods accordingly for each new command and itself it just feels not efficient.

So I wanted to ask if it is possible to maybe use a Map with a key, the String of the user input on my scanner, and the start the method dynamically as the value of the map.

Like:

HashMap<String, Method> test = new HashMap<>();
test.put("test", test());

I tried to do that but it didnt work out, since my test() method had to return another method which did not make sense to me.
Does anyone have any suggestions on how to fix that problem?

Cheers

答案1

得分: 1

定义一个名为Command的接口,代表执行的动作。然后,您可以将相关的Command存储在Map中,其中别名作为键。请随意查阅命令模式,它可能具有一些更有用和常规的设计。

interface Command {

    void execute();

}

class MyCommand implements Command {

    @Override
    public void execute() {

    }
}
Map<String, Command> commands = new HashMap<>();

commands.put("command", new MyCommand());

commands.put("helloWorld", () -> System.out.println("Hello World"));

Command command = commands.get("command");

Command helloWorld = commands.get("helloWorld");

command.execute();

helloWorld.execute();
英文:

Define an interface called Command that will represent the action performed. You can then store the relevant Command in a Map with the alias as the key. Feel free to look into the command pattern, it might have some more useful and conventional design.

interface Command {
        
    void execute();
        
}
    
class MyCommand implements Command {

    @Override
    public void execute() {
            
    }
}
Map&lt;String, Command&gt; commands = new HashMap&lt;&gt;();
        
commands.put(&quot;command&quot;, new MyCommand());

commands.put(&quot;helloWorld&quot;, () -&gt; System.out.println(&quot;Hello World&quot;));
        
Command command = commands.get(&quot;command&quot;);

Command helloWorld = commands.get(&quot;helloWorld&quot;);
        
command.execute();

helloWorld.execute();

huangapple
  • 本文由 发表于 2020年7月22日 20:10:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/63033889.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定