Presentation is loading. Please wait.

Presentation is loading. Please wait.

Presentation by Julie Betlach 7/02/2009

Similar presentations


Presentation on theme: "Presentation by Julie Betlach 7/02/2009"— Presentation transcript:

1 Presentation by Julie Betlach 7/02/2009
GoF Interpreter (pp ) Presentation by Julie Betlach 7/02/2009

2 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.

3 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:

4 Interpreter Structure
Picture & Example from:

5 Composite Structure Looks a lot like Composite Structure…
Picture & Example from:

6 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'

7

8 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

9 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


Download ppt "Presentation by Julie Betlach 7/02/2009"

Similar presentations


Ads by Google