tags:

views:

78

answers:

3

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.

  1. Create action classes for each command. Each will have a Execute() method and implements an interface IExecutable. So if I have 5 commands, I will have 5 classes each for processing each command.
  2. Keep the command and associated object that can perform action in an associative container (std::map in C++ and Dictionary in .NET).
  3. Loop through each character in the input string. Check any action associated for each character. If yes, get the action object and call Execute(). Some sort of command design pattern. If some charcters don't have action associated, throw error or skip.

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?

A: 

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.

CookieOfFortune
+3  A: 

Yep. That's exactly how I'd do it, except using Runnable::run() instead of IExececutable::Execute().

Michael Aaron Safyan
A: 

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.

Partial