Presentation by Julie Betlach 7/02/2009 GoF Interpreter (pp. 243-255) Presentation by Julie Betlach 7/02/2009
Interpreter Pattern - Intent / Applicability Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language. Applicability – Use Interpreter Pattern… The grammar is simple Parser generators are a better alternative. Efficiency is not a critical concern Not usually efficient to parse trees directly. Translate them into another form. Consider transforming regular expressions into state machines first. But even then, the translator can be implemented by the Interpreter Pattern.
Motivation The following Reverse Polish notation example illustrates the interpreter pattern. The grammar below: expression ::= plus | minus | variable plus ::= expression expression '+' minus ::= expression expression '-' variable ::= 'a' | 'b' | 'c' | ... | 'z' defines a language which contains reverse polish expressions like: a b + a b c + - a b + c a - - Picture & Example from: http://en.wikipedia.org/wiki/Interpreter_pattern
Interpreter Structure Picture & Example from: http://en.wikipedia.org/wiki/Interpreter_pattern
Composite Structure Looks a lot like Composite Structure… Picture & Example from: http://en.wikipedia.org/wiki/Interpreter_pattern
Structure A class is used to represent each grammar rule. expression ::= plus | minus | variable plus ::= expression expression '+' minus ::= expression expression '-' variable ::= 'a' | 'b' | 'c' | ... | 'z'
It’s easy to change and extend the grammar Consequences Good It’s easy to change and extend the grammar Implementing the grammar is easy Easy to evaluate an expression in a new way Examples: pretty printing or type checking If you keep adding new ways to evaluate an expression, consider using Visitor Bad Complex grammars are hard to maintain One class for each rule
Composite – Abstract syntax tree is an instance of Composite Pattern Related Patterns Composite – Abstract syntax tree is an instance of Composite Pattern Flyweight – Shows how to share terminal symbols within the abstract syntax tree Iterator – The interpreter can use an iterator to traverse the structure Visitor – Can be used to maintain the behavior in each node in the abstract syntax tree in one class