Interpreter (wzorzec projektowy)/kod
Z Wikiźródeł, repozytorium wolnych materiałów źródłowych
| Interpreter (wzorzec projektowy) Kod źródłowy |
|||
Kody źródłowe programów stosujących wzorzec projektowy interpretera
|
[edytuj] Java
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.parseInt(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()); } }
Udziela się zgody na kopiowanie, dystrybucję i/lub modyfikację tego tekstu na warunkach licencji GNU Free Documentation License w wersji 1.2 lub nowszej, opublikowanej przez Free Software Foundation.
Kopia tekstu licencji umieszczona została pod hasłem GFDL. Dostepne jest również jej polskie tłumaczenie.