It is generally used in the development of the compiler in OOP development, so the application surface is rather narrow.
Public interface Expression {public int interpret (context context);}
public class Plus implements expression{@Overridepublic int interpret (context context) {//TODO auto-generated method stub Return Context.getnum1 () +context.getnum2 ();}}
public class minus implements expression{@Overridepublic int interpret (context context) {//TODO auto-generated method Stu Breturn context.getnum1 ()-context.getnum2 ();}}
public class Context {private int num1, Num2;public int getNum1 () {return NUM1;} public int getNum2 () {return num2;} public void setNum1 (int num) {this.num1 = num;} public void setNum2 (int num) {this.num2 = num;} Public Context (int num1, int num2) {this.num1 = num1;this.num2 = num2;}}
Test class:
/** * Parser Mode * @author Administrator * */public class Test {public static void main (string[] args) {//TODO auto-generated Method stub//Calculates 9+8-7int result = new minus (). Interpret (new context (new Plus (). Interpret (new context (9, 8)), 7) )); SYSTEM.OUT.PRINTLN (result); }}
Final output correct result: 10
Basically, the interpreter pattern is used to make all kinds of interpreters, such as regular expressions and so on!
Interpreter mode (interpreter)