Interpreter Pattern Article Index for
Interpreter
Website Links For
Pattern
 

Information About

Interpreter Pattern





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:

  • --- one to define data,

  • --- one to define operations on the data,

  • --- one to define when to perform the operations,

  • --- and at least one to define how to translate the computer program to machine language.



EXAMPLES



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 2 1 - +' equals to 43".

  • ;


''interface Expression'' {
public void interpret(Stack s);
}

class TerminalExpression_Number ''implements Expression'' {
private int number;
public TerminalExpression_Number(int number) { this.number = number; }
public void interpret(Stack s) { s.push(number); }
}

class TerminalExpression_Plus ''implements Expression'' {
public void interpret(Stack s) { s.push( s.pop() + s.pop() ); }
}

class TerminalExpression_Minus ''implements Expression'' {
public void interpret(Stack s) { int tmp = s.pop(); s.push( s.pop() - tmp ); }
}

class Parser {
private ArrayList parseTree = new ArrayList(); ''// 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 context = new Stack();
for (Expression e : parseTree) e.interpret(context);
return context.pop();
}
}

class InterpreterExample {
public static void main(String {Link without Title} args) {
System.out.println("'42 2 1 - +' equals to " + new Parser("42 2 1 - +").evaluate());
}
}


SEE ALSO