Download Interpreter Pattern

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Pattern language wikipedia , lookup

Representation (arts) wikipedia , lookup

Transcript
Interpreter
CS 124
Reference: Gamma et al
(“Gang-of-4”), Design Patterns
Some material taken from:
http://www.dofactory.com/Patterns/PatternInterpreter.aspx
Interpreter

Intent


Given a language, define a representation for its grammar
along with an interpreter that uses the representation to
interpret sentences in the language
Motivation


Interpreting and evaluating expressions governed by a
rules of some language is a common programming
problem
 e.g., arithmetic expressions, regular expressions
This pattern provides a way to define the grammar for the
language, represent sentences, and then interpret those
sentences
Design Solution
Participants



Client, context, expression
Client typically calls an evaluate method on
the context object
The call, in turn, calls interpret on several
expression objects, and culminates in a
returned result

The expression objects together represent the
entire sentence, and hence are usually contained
in another object
Examples

Roman numeral parsing:


From http://www.dofactory.com/Patterns/PatternInterpreter.aspx
Simple arithmetic expression parsing:


Reverse polish notation
From
http://en.wikipedia.org/wiki/Interpreter_pattern
Example: parsing
arithmetic expressions





Client (InterpreterDemo) creates Parser
object using input sentence
Client calls evaluate() on the Parser object
Parser contains a context object (a Stack)
and a list of Expression objects
evaluate() calls interpret(context) on each
Expression object
Desired result is returned via the context
object
Related Patterns

The expression structure follows the
Composite pattern