| Interpreter Pattern |
Article Index for Interpreter |
Website Links For Pattern |
Information AboutInterpreter Pattern |
| CATEGORIES ABOUT INTERPRETER PATTERN | |
| software design patterns | |
| articles with example java code | |
|
USES FOR THE INTERPRETER PATTERN
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 } class TerminalExpression_Number ''implements Expression'' { private int number; public TerminalExpression_Number(int number) { this.number = number; } public void interpret(Stack } class TerminalExpression_Plus ''implements Expression'' { public void interpret(Stack } class TerminalExpression_Minus ''implements Expression'' { public void interpret(Stack } class Parser { private ArrayList 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 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
|
|
|