Interpreter pattern

From Wikipedia, the free encyclopedia

In computer programming, the interpreter pattern is a particular design pattern. The basic idea is to implement a specialized computer language to rapidly solve a defined class of problems. Specialized languages often let a problem be solved several to several hundred times more quickly than a general purpose language would permit.

The general idea is to have a class for each symbol (terminal or nonterminal) in the language.

Contents

[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

[edit] Java

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