I am working on a transliteration tool. I have two modules lexer and translator. Lexer generates tokens out of the input text. Depending on the current language chosen, I have to call appropriate translation routine.
I have came up with couple of ideas to do this. First one is to create a base class something called base_translator
and provide virtual method (translate()
) which every translators has to override. Now create a factory translator_factory
and call create()
with the language name. This factory will return appropriate instance.
But this seems to be over engineering. So I came up with another approach where I have a struct like the following.
struct translator
{
const char* name;
void (*fp)();
};
Which just keeps a language name and a function pointer who can process it. Usage will be,
static translator translators[] = {
{"first", first},
{"second", second}
};
const char* language = /* */;
for(int i = 0; i < 2; i++) {
translator *t = translators + i;
if(strcmp(t->name, language) == 0) {
t->fp();
break;
}
}
This approach is very simple and easy to maintain. But I wonder, is this the best approach to the problem? Do you have any suggestions to make this better?
Any help would be great.