Design Pattern Notes 21 - Interpreter Mode (interpreter)

four arithmetic problems

Realize the four arithmetic operations through the interpreter mode, such as calculating the value of a+bc, specific requirements

1) First enter the form of the expression, such as a+b+c-d+e, and the letters of the expression must not be repeated

2) Enter the values ​​of a, b, c, d, e respectively

3) Finally find the result:

 

 

Analysis of traditional solutions to solve four arithmetic problems

1) Write a method to receive the form of the expression, and then analyze it according to the value entered by the user to get the result

2) Problem analysis: If new operators are added, such as * / (, etc., it is not conducive to expansion, and another method to analyze will cause confusion in the program structure and is not clear enough.

3) Solution: You can consider using the interpreter mode, namely: expression -> interpreter (can have multiple) -> result

 

Basic introduction to interpreter mode

1) In the compilation principle, an arithmetic expression forms a lexical unit through a lexical analyzer, and then these lexical units are then used to construct a grammatical analysis tree through a lexical analyzer, and finally form an abstract lexical analysis tree. Both the lexical analyzer and the syntax analyzer here can be regarded as interpreters

2) Interpreter Pattern: Given a language (expression), define a representation of its grammar, and define an interpreter, use the interpreter to interpret sentences (expressions) in the language

3) Application scenarios

• The application can represent a sentence in a language that needs to be interpreted as an abstract syntax tree

• Some recurring questions can be expressed in a simple language

• A scenario where simple syntax requires explanation

4) There are also such examples, such as compilers, calculation of arithmetic expressions, regular expressions, robots, etc.

 

 

Principle class diagram of interpreter mode

Explanation of the principle class diagram - that is (the role and responsibility of the interpreter mode)

1) Context: is an environment role, containing global information outside the interpreter.

2) AbstractExpression: abstract expression, declares an abstract interpretation operation, this method is shared by all nodes in the abstract syntax tree

3) TerminalExpression: It is a terminal expression, which implements the interpretation operation related to the terminal in the grammar

4) NonTermialExpression: It is a non-terminal symbol expression, and realizes the interpretation operation for the non-terminal symbols in the grammar.

5) Note: Enter the Context and TerminalExpression information through the Client input

 

The core code, taking 2+2 as an example, can be parsed into an expression that can be calculated, and the interpreter can be used:

For a 2+2 expression, use Stack to split the expression into left and right sides:

    public Calculator(String expStr) { // expStr = a+b
        // Arrange the sequence of operations
        Stack<Expression> stack = new Stack<>();
        // Expression is split into character array 
        char[] charArray = expStr.toCharArray (); // [a, +, b]

        Expression left = null;
        Expression right = null;
        // Traversing our character array, that is, traversing [a, +, b]
        // Do processing for different situations
        for (int i = 0; i < charArray.length; i++ ) {             switch (charArray[i]) {             case '+': //                 left = stack.pop();// take out from stack left => "a"                 right = new VarExpression(String.valueOf(charArray[++i ]));// Take out the right expression "b"                 stack.push(new AddExpression(left, right));// Then build AddExpresson and add stack according to the obtained left and right                 break;             case '-': //                  left = stack .pop();                 right = new VarExpression(String. valueOf(charArray[++i]));









                stack.push(new SubExpression(left, right));
                break;
            default: 
                //If it is a Var, create a VarExpression object and push it to the stack
                stack.push(new VarExpression(String.valueOf(charArray[i]) ));
                break;
            }
        }
        //After traversing the entire charArray array, the stack will get the last Expression
        this.expression = stack.pop();
    }

After that, the addition expression is used to add the left and right sides together. A method that splits one at a time and then returns a phase+ or phase-. Relevant algorithms refer to the use of the stack for the four arithmetic operations, and the interpreter quite encapsulates this series of algorithms.
    public int interpreter(HashMap<String, Integer> var) {         return super. left. interpreter(var) + super. right. interpreter(var);     }

 

 

Notes and Details of Interpreter Mode

1) When there is a language that needs to be interpreted and executed, the sentences in the language can be represented as an abstract syntax tree, and the interpreter mode can be considered to make the program have good scalability

2) Application scenarios: compilers, calculation of arithmetic expressions, regular expressions, robots, etc.

3) Problems that may be caused by using an interpreter: The interpreter mode will cause class expansion, and the interpreter mode uses recursive call methods, which will lead to very complicated debugging and may reduce efficiency.

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_22059611/article/details/103305421