Java – iterative execution command list – which mode?

I wrote a java program that reads a file containing the commands to be executed (in my own language) Command is read as a string and placed in an array Now, the "scheduler" - Method loops through the array, interprets the command, and calls the corresponding method that will perform the operation on it

This of course leads to a lot of nested if statements:

if commandReadIn == this,do that... 
if commandReadIn is of type x,get next element,treat next element as argument... 
etc.

Now I only have some commands, but what if I want to add hundreds? The code will become unmaintainable

Now I wonder if I can get rid of conditional logic completely The command mode here seems useless because I have to interpret the string at some point This means a lot of nested "if" If not, what is the best way to refactor commands and their syntax in a way that makes it easy to add, edit, or delete commands?

Solution

Use command pattern as the command Your implementation can be greatly simplified

1) Use the execute method to create the command interface 2) Create an implementation for each command 3) When you start the program, create a command string mapping – > command implementation 4) When you read the string, look for the corresponding implementation and call it 5) Optionally, your execute method can take a custom context object as a parameter, allowing you to pass command parameters in a generic way The implementation understands the context object and retrieves parameters from it

With this method, you will not have an IF statement except to check that you cannot retrieve anything from the cache of the command implementation

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>