One, interpreter mode (interpreter)
Interpreter mode is generally used in the development of the compiler in OOP development, so the application surface is narrower.
The context class is a contextual class, plus and minus are used to calculate the implementation, the code is as follows:
- Public interface Expression {
- public int interpret (context context);
- }
- public class Plus implements Expression {
- @Override
- public int interpret (context context) {
- Return Context.getnum1 () +context.getnum2 ();
- }
- }
- public class minus implements Expression {
- @Override
- public int interpret (context context) {
- Return Context.getnum1 ()-context.getnum2 ();
- }
- }
- public class Context {
- private int num1;
- private int num2;
- Public Context (int num1, int num2) {
- THIS.NUM1 = NUM1;
- this.num2 = num2;
- }
- public int getNum1 () {
- return NUM1;
- }
- public void setNum1 (int num1) {
- THIS.NUM1 = NUM1;
- }
- public int getNum2 () {
- return num2;
- }
- public void setNum2 (int num2) {
- this.num2 = num2;
- }
- }
- public class Test {
- public static void Main (string[] args) {
- Calculate the value of a 9+2-8
- int result = new minus (). Interpret (new Context (New Plus ()
- . Interpret (new Context (9, 2)), 8));
- SYSTEM.OUT.PRINTLN (result);
- }
- }
Finally output the correct result: 3.
Basically, the interpreter pattern is used to make all kinds of interpreters, such as regular expressions and so on!
Reprinted from Https://www.cnblogs.com/maowang1991/archive/2013/04/15/3023236.html
-------Interpreter for Java 23 design Patterns