Card 02/ 08

ConceptDifficulty: Intermediate1 min

Interpreter Pattern Structure: The Class Diagram

AbstractExpression, TerminalExpression, NonterminalExpression and a Context passed to interpret().

Interpreter has four participants: the abstract expression, terminal expressions, non-terminal expressions, and a context. This card reads their roles off the Gang of Four's class diagram, matches each class to a rule of the grammar, and draws the tree for one sentence.

Interpreter participants
Each participant and its role
ParticipantRoleIn arithmetic
Abstract ExpressionDeclares interpret(context).Expression
Terminal ExpressionA leaf: a rule with no smaller expression inside, evaluated on its own.Number, Variable
Non-terminal ExpressionA rule built from other expressions; it interprets its parts and combines the results.Add, Multiply
ContextWhat the sentence is evaluated against, such as the values of its variables.Context, holding x

The names come from grammars. A terminal is a symbol that appears in a sentence as it is, such as a number or a variable name; a non-terminal is a rule that stands for a combination of other symbols, such as "an addition is an expression, a plus sign, and an expression". The class diagram is the Composite pattern's: non-terminal expressions hold other expressions, and every expression, leaf or not, has the same interpret.

The sentence 1 + 2 * x becomes the tree below. Multiplication sits lower because it is evaluated first, and the root is the last operation performed.

The tree for 1 + 2 * x

Evaluating the root asks each child for its value, down to the leaves, and combines the answers on the way back up. With x set to 3, Multiply returns 6, and Add returns 7.