- Interpreter pattern is a design pattern that specifies how to evaluate sentences in a language.
- The basic idea is to have a class for each symbol (terminal or nonterminal) in a specialized computer language.
- The syntax tree of a sentence in the language is an instance of the composite pattern and is used to evaluate (interpret) the sentence.
Uses for the Interpreter pattern
Specialized database query languages such as SQL.
Specialized computer languages which are often used to describe communication protocols.
Most general-purpose computer languages actually incorporate several specialized languages.
Structure
The following Reverse Polish notation example illustrates the interpreter pattern. The grammar
expression ::= plus | minus | variable | number
plus ::= expression expression '+'
minus ::= expression expression '-'
variable ::= 'a' | 'b' | 'c' | ... | 'z'
digit = '0' | '1' | ... '9'
number ::= digit | digit number
defines a language which contains reverse Polish expressions like:
a b +
a b c + -
a b + c a - -
#include <string>
#include <iostream>
#include <stdexcept>
class Interpreter
{
public:
template<typename It>
void run(It from, It to)
{
for(It i=from; i!=to; ++i)
{
switch(*i)
{
case 'h': std::cout << "Hello";
break;
case ' ': std::cout << ' ';
break;
case 'w': std::cout << "world";
break;
case '!': std::cout << '!';
break;
case 'n': std::cout << std::endl;
break;
default:
throw std::runtime_error("Unknown command");
}
}
}
};
void hello_world(const std::string & script)
{
Interpreter().run(script.begin(), script.end());
}
int main()
{
hello_world("h w!n");
return 0;
}