Interpreter
Definition
Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
UML class diagram
Participants
- AbstractExpression
- declares an interface for executing an operation
- TerminalExpression
HundredExpression, TenExpression, OneExpression )
- implements an Interpret operation associated with terminal symbols in the grammar.
- an instance is required for every terminal symbol in the sentence.
- NonterminalExpression
- implements an Interpret operation for nonterminal symbols in the grammar.
- Context
- contains information that is global to the interpreter
- Client
- builds an abstract syntax tree representing a particular sentence in the language that the grammar defines. The abstract syntax tree is assembled from instances of the NonterminalExpression and TerminalExpression classes
- invokes the Interpret operation
Sample code in Java
package com.hong.interpreter; import java.util.ArrayList; class Context { } interface AbstractExpression{ void interpret(Context context); } class TerminalExpression implements AbstractExpression { @Override public void interpret(Context context) { System.out.println("Interpret from Terminal-expression"); } } class NonterminalExpression implements AbstractExpression{ @Override public void interpret(Context context) { System.out.println("Interpret from Non-terminal expression"); } } public class InterpreterStructure { public static void main(String[] args) { Context context = new Context(); ArrayList<AbstractExpression> expressions = new ArrayList<AbstractExpression>(); expressions.add(new TerminalExpression()); expressions.add(new NonterminalExpression()); expressions.add(new TerminalExpression()); expressions.add(new TerminalExpression()); for(AbstractExpression exprs : expressions) { exprs.interpret(context); } } }