I have a program which gets commands as a string. Each character in the string represents a command. An example of command is given below
OBIPC
O - Open a file
B - Make the text in Bold
I - Make the text in italics
P - Print the text
C - Close the file
My program has to parse this string and do respective job. Each command is executed sequentially. I came up with the following idea to do this.
Will this approach be the best for my problem or do you see any easy/efficient method to do this? This is not specific to any programming language, I am OK with any programming language. All I am looking for is ideas to do this.
Any thoughts?
Yep. That's exactly how I'd do it, except using Runnable::run() instead of IExececutable::Execute().
A lot of scripting languages allow you to call an eval() like function, which will essentially run a string as code. That's probably the easiest way to do something like that... and also the least safe.
Do you really need 5 classes for each command? You could create an interface in a .h that exposes a function that takes the string has a parameter. In a .cpp you could have a class that inherits from the interface. The class hidden behind would have the job to analyse the string and throw an exception in case it contains a character that has nothing to do with the commands (does the order of the characters matter?). Once the analysis is over it could call a class function for each command.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.