Interpreter Pattern - Behavioural!: - Intent"
Interpreter Pattern - Behavioural!: - Intent"
• Intent"
» Given a language, define a representation for tis
grammar along with an interpreter that uses the
representation to interpret sentences in the
language!
Interpreter-1
Motivation!
Interpreter-2
Example Searching for Substrings!
Legend!
Space !means ʻandʼ!
, !(comma) means ʻorʼ!
(…) !(must choose) means choose one ! +(…) means choose one or more !
[…] !(optional) means choose one or none! +[…] means choose zero or more!
!
Interpreter-4
Example Architecture!
ALTERNATION_EXPRESSION SEQUENCE_EXPRESSION
interpret interpret
alternative_2 expression_2
REGULAR_EXPRESSION
alternative_1 interpret expression_1
repetiton
REPETITION_EXPRESSION LITERAL_EXPRESSION
interpret interpret
NONE
literal
Interpreter-5
Example Abstract Syntax Tree!
aSequenceExpression
expression_1
expression_2
aLiteralExpression aSequenceExpression
"raining" repetition
anAlternativeExpression
alternative_1
altlernative_2
aLiteralExpression aLiteralExpression
"cats" "dogs"
Interpreter-6
Abstract Architecture!
CONTEXT
context ABSTRACT_EXPRESSION
expression interpret(context)
CLIENT
TERMINAL_EXPRESSION NONTERMINAL_EXPRESSION
interpret(context) interpret(context)
Interpreter-7
Scenario!
Scenario: Interpret!
1! 2!
ABSTRACT_SYNTAX_TREE! INTERPRET!
Interpreter-8
Participants!
• AbstractExpression"
» Declares an abstract Intepret operation that is
common to all nodes in the abstract syntax tree!
"
• TerminalExpression"
» Implements an Interpret operation associated with
terminal symbols in the grammar!
• Context"
» Contains information thatʼs global to the interpreter!
Interpreter-9
Participants – 2!
• NonTerminalExpression"
» One class required for each non-terminal in the
grammar!
» Maintains instance variables for sub-expressions!
» Implements an Interpret operation for nonterminal
symbols in the grammar!
• Client"
» Builds / gets an abstract syntax tree for a sentence
in the language!
» Invokes the interpret operation!
Interpreter-10
Applicability!
Interpreter-11
Consequences!
Interpreter-12
Consequences – 2!
Interpreter-13
Related Patterns!
Interpreter-14
Interpreter in Java API!
Interpreter-15