Interpreter mode: Creates an interpreter for the language, providing a way to evaluate the language's syntax or expression.
Example:
Public InterfaceExpression { Public Abstract Booleaninterpret (String context); Public classTerminalexpressionImplementsExpression {PrivateString data; Publicterminalexpression (String data) { This. data =data; } @Override Public Booleaninterpret (String context) {if(Context.contains (data)) {return true; } return false; }} Public classOrexpressionImplementsExpression {PrivateExpression Exp1; PrivateExpression Exp2; Publicorexpression (expression exp1, expression Exp2) { This. EXP1 =EXP1; This. EXP2 =EXP2; } @Override Public Booleaninterpret (String context) {returnExp1.interpret (context) | |Exp2.interpret (context); }} Public classAndexpressionImplementsExpression {PrivateExpression Exp1; PrivateExpression Exp2; Publicandexpression (expression exp1, expression Exp2) { This. EXP1 =EXP1; This. EXP2 =EXP2; } @Override Public Booleaninterpret (String context) {returnExp1.interpret (context) &&Exp2.interpret (context); }} Public classTest { Public Staticexpression getmaleexpression () {expression Robert=NewTerminalexpression ("Robert"); Expression John=NewTerminalexpression ("John"); return Neworexpression (Robert, John); } Public Staticexpression getmarriedwomanexpression () {expression Julie=NewTerminalexpression ("Julie"); Expression married=NewTerminalexpression ("Married"); return Newandexpression (julie,married); } Public Static voidMain (string[] args) {Expression Ismale=getmaleexpression (); System.out.println (Ismale.interpret ("John")); Expression Ismarriedwoman=getmarriedwomanexpression (); System.out.println (Ismarriedwoman.interpret ("Married Julie")); }}
Test results:
In Java, where there is little use of the interpreter pattern, the EXPRESSION4J framework is a Java-based open-source framework that operates on mathematical expressions and is a mathematical equation parser. It is the best example of applying the interpreter pattern, but the framework is still in the process of being perfected.
Interpreter mode (interpreter pattern)