Would love some opinions on this problem I'm trying to workout. I'm trying to improve my OO experience and fully leverage C++'s polymorphic capabilities. I'm trying to write some code for a basic command parser. They command structure goes as so:
[command name] [arguments]
The command name will just be limited to a one word string. The arguments can be a 0 to N list of strings.
Each command and list of arguments could be directed to any variety of software objects in my system. So for example I could have an rtp statistics command map to my rtp module, the user statistics to my user module. Something like that.
Right now the entry point for my CLI provides the entire command string as a standard string. And it provides a standard output stream for displaying results to the user.
I really want to avoid using a parser function and then doing an if then else kind of deal. So I was thinking something like this:
What I'm struggling with is how to give the right module to the right command. Is this where I should use a template argument? So that each command can take any interface and I'll let the factory decide which module to pass in to the command object?
I'm also open to other opinions as well. I'm just trying to learn and hoping the community can give me some tips :-).
What you're looking for is a common pattern in OOP. Design Patterns (the Gang of Four book) referred to this as a Command Pattern.
There's generally no need for templates. Everything is parsed and dispatched at runtime, so dynamic polymorphism (virtual functions) is probably a better choice.
In another answer, Rafael Baptista suggested a basic design. Here is how I would modify his design to be more complete:
Commands are handled by subclasses of the Command
class. Commands are dispatched by a CommandDispatcher
object that handles the basic parsing of the command string (basically, splitting at spaces, possibly handling quoted strings, etc.).
The system registers an instance of Command
with the CommandDispatcher
, and associates each instance of Command
with a command name (std::string
). The association is handled by a std::map
object, although that could be replaced by a hash table (or similar structure to associate key-value pairs).
class Command
{
public:
virtual ~Command(void);
virtual void execute(FILE* in, const std::vector<std::string>& args) = 0;
};
class CommandDispatcher
{
public:
typedef std::map<std::string, Command*> CommandMap;
void registerCommand(const std::string& commandName, Command* command)
{
CommandMap::const_iterator cmdPair = registeredCommands.find(commandName);
if (cmdPair != registeredCommands.end())
{
// handle error: command already registered
}
else
{
registeredCommands[commandName] = command;
}
}
// possibly include isRegistered, unregisterCommand, etc.
void run(FILE* in, const std::string& unparsedCommandLine); // parse arguments, call command
void dispatch(FILE* in, const std::vector<std::string>& args)
{
if (! args.empty())
{
CommandMap::const_iterator cmdPair = registeredCommands.find(args[0]);
if (cmdPair == registeredCommands.end())
{
// handle error: command not found
}
else
{
Command* cmd = cmdPair->second;
cmd->execute(in, args);
}
}
}
private:
CommandMap registeredCommands;
};
I've left the parsing, and other details out, but this is a pretty common structure for command patterns. Notice how the std::map
handles associating the command name with the command object.
To make use of this design, you need to register commands in the system. You need to instantiate CommandDispatcher
, either using a Singleton pattern, in main
, or in another central location.
Then, you need to register the command objects. There are several ways to do this. The way I prefer, because you have more control, is to have each module (set of related commands) provide its own registration function. For example, if you have a 'File IO' module, then you might have a function fileio_register_commands
:
void fileio_register_commands(CommandDispatcher* dispatcher)
{
dispatcher->registerCommand( "readfile", new ReadFileCommand );
dispatcher->registerCommand( "writefile", new WriteFileCommand );
// etc.
}
Here ReadFileCommand
and WriteFileCommand
are subclasses of Command
that implement the desired behavior.
You have to make sure to call fileio_register_commands
before the commands become available.
This approach can be made to work for dynamically loaded libraries (DLLs or shared libraries). Make sure that the function to register commands has a regular pattern, based on the name of the module: XXX_register_commands
, where XXX
is, for example, the lower cased module name. After you load the shared library or DLL, your code can determine whether such a function exists, and then call it.
Templates is overkill. I imagine you want something where the command interpreter just figures out what commands are possible from the objects that are available.
For each class that wants to support this CLI, I'd give it a function that registers the class, and the command name that triggers that class.
class CLIObject
{
virtual void registerCli( Cli& cli ) = 0;
virtual bool doCommand( FILE* file, char** args ) = 0;
}
class HelloWorld : public ClIObject
{
void registerCli( Cli& cli ) { cli.register( this, "helloworld" ); }
bool doCommand( FILE* file, char** args )
{
if ( !args[0] ) return false;
fprintf( file, "hello world! %s", args[0] );
return true;
}
}
Now your cli can support any class that derives from CLIObject.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With