Interpreter pattern

From Wikipedia, the free encyclopedia

Jump to: navigation, search

In computer programming, the interpreter pattern is a particular design pattern. The basic idea is to have a class for each symbol (terminal or nonterminal) in a specialized computer language, so that the language's syntax tree is an instance of the composite pattern. The interpreter pattern specifies how to evaluate language constructs.

Contents

[edit] Structure

Image:Interpreter_UML_class_diagram.jpg

[edit] Uses for the Interpreter pattern

  • Specialized database query languages such as SQL.
  • Specialized computer languages which are often used to describe communication protocols
  • Most general-purpose computer languages actually incorporate several specialized languages.

[edit] Examples

The following Java example illustrates how a general purpose language would interpret a more specialized language, here the Reverse Polish notation. The output is:

'42 4 2 - +' equals 44
import java.util.*;
 
interface Expression {
    public void interpret(Stack<Integer> s);
}
 
class TerminalExpression_Number implements Expression {
    private int number;
    public TerminalExpression_Number(int number)       { this.number = number; }
    public void interpret(Stack<Integer> s)  { s.push(number); }
}
 
class TerminalExpression_Plus implements Expression {
    public void interpret(Stack<Integer> s)  { s.push( s.pop() + s.pop() ); }
}
 
class TerminalExpression_Minus implements Expression {
    public void interpret(Stack<Integer> s)  { s.push( - s.pop() + s.pop() ); }
}
 
class Parser {
    private ArrayList<Expression> parseTree = new ArrayList<Expression>(); // only one NonTerminal Expression here
 
    public Parser(String s) {
        for (String token : s.split(" ")) {
            if      (token.equals("+")) parseTree.add( new TerminalExpression_Plus() );
            else if (token.equals("-")) parseTree.add( new TerminalExpression_Minus() );
            // ...
            else                        parseTree.add( new TerminalExpression_Number(Integer.valueOf(token)) );
        }
    }
 
    public int evaluate() {
        Stack<Integer> context = new Stack<Integer>(); 
        for (Expression e : parseTree) e.interpret(context);
        return context.pop();
    }
}
 
class InterpreterExample {
    public static void main(String[] args) {
        String expression = "42 4 2 - +";
        Parser p = new Parser(expression);
        System.out.println("'" + expression +"' equals " + p.evaluate());
    }
}

[edit] See also


Personal tools