design patterns
Interpreter
The Interpreter pattern defines a representation of a grammar for a given language and provides an interpreter to evaluate sentences in that language. It maps each grammar rule to a class. The key participants are the AbstractExpression (declares an interpret operation), TerminalExpression (implements interpret for terminal symbols in the grammar), NonterminalExpression (implements interpret for nonterminal grammar rules, typically composed of other expressions), and Context (contains global information needed during interpretation). Think of a calculator: numbers are terminal expressions and operators (+, -, *) are nonterminal expressions that combine terminals. Use Interpreter when you have a simple grammar that you need to interpret and the grammar is stable — for complex grammars, consider parser generators instead.
Use Cases
- •Simple expression evaluators and calculators
- •SQL-like query language parsing
- •Regular expression engines
- •Configuration file parsers with custom syntax