如何以优雅的方式从不同的说明/规则切换
希望您的帮助! 我正在进行一个重现徽标语言的Java项目,因为我找不到优雅而不是太复杂的方式来切换不同规则 /说明,该项目的重点是高级编程,并且使用流()是建议;谓词();功能 ();双方函数()ect等。这是我已经实施的指令列表,但我不知道如何分支它们,我将它们作为字符串:
- forward(int);
- 向后(int);
- 左(int);
- 正确(int);
- 透明屏;
- 家;
- pen
- Pendown;
- setPencolor(int)(int)(int);
- setFillColor(int)(int)(int);
- setScreencolor(int)(int)(int);
- setPensize(int);
- ripeti(int)[(cmds)];
- 在命令列表(CMDS)中重复命令的顺序
重复我想到的
hoping for your help!
I'm doing a java project that reproduces the logo language and im capped as I can't find an elegant and not too complicated way to switch between different rules / instructions, the project focuses on advanced programming and the use of Stream () is suggested; Predicate (); Function (); BiFunction () ect etc this is the list of instructions that I have implemented but that I have no idea how to branch them, i take them as a String:
- FORWARD (int);
- BACKWARD (int);
- LEFT (int);
- RIGHT (int);
- CLEARSCREEN;
- HOME;
- PENUP;
- PENDOWN;
- SETPENCOLOR (int) (int) (int);
- SETFILLCOLOR (int) (int) (int);
- SETSCREENCOLOR (int) (int) (int);
- SETPENSIZE (int);
- RIPETI (int) [ (cmds) ];
- Repeats the sequence of commands in the command list (cmds)
I have thought of an if () else () or a switch () but it does not seem very elegant
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果开关可以正常工作,但您不希望该方法具有太多的行,则可以尝试使用映射,从字符串到方法调用(可以使用lambdas),或者从枚举值或从枚举值到相同。
或
请注意,在第二个示例中,我使用了对操作对象的调用的方法参考,我认为您目前有一个实例。
问题是,您的指令采用不同数量的参数,因此这实际上只是解决方案的草图。您必须弄清楚如何将其应用于用例。特别是,您尚未提及操作方法如何接受参数。我想每个每个参数都取决于指令,为0、1或多个参数。
您可以做的一件事是将每个命令解析到该命令的枚举实例中,并将任何参数分解为单独的对象。也许是
列表< integer>
。我不知道您是否可以修改操作类以接受该列表而不是单个参数。或者可以将其修改为将例如forward(int ... params)
进行,然后您可以传递参数的int []
。希望这至少会给您一些想法,这些想法会让您解开。
If a switch would work but you don't want the method to have too many lines, you could try using a map, either from String to method calls (for which you could use lambdas), or from Enum values to the same.
Or
Note that in the second example I used method references for the calls to the Action object, which I'm assuming you have an instance of at this point.
The problem is, your instructions take different numbers of parameters, so that is really just a sketch of a solution. You'll have to figure out how to apply it to your use case. In particular, you haven't mentioned how the Action methods accept the parameters. I suppose each one takes 0, 1, or multiple parameters, depending on the instruction.
One thing you could do is parse each command into an Enum instance for that command, and any parameters into a separate object; maybe a
List<Integer>
. I don't know if you can modify the Action class to accept that list instead of the individual parameters. Or maybe modify it to take e.g.forward(int... params)
and you could then pass anint[]
of the parameters.Hopefully this will at least give you some ideas that will get you unstuck.