Tenth chapter, Interpreter mode
The interpreter pattern is a relatively small, behavioral pattern that provides a way to interpret a language's syntax or expression. But its use is quite extensive, just because we seldom go back and construct a language grammar, so we use less.
1. Definition
Given a language, define a representation of its grammar and define an interpreter that uses that representation to interpret sentences in the language. (where language is the object we need to explain, grammar is the law of the language, the interpreter is the translator, and the language is translated by grammar.) )
2. Usage Scenarios
1. Consider using the interpreter pattern if a simple language needs to interpret execution and can represent statements in that language as an abstract syntax tree.
2. When there are recurring problems in certain areas, you can convert the problem in this area into a statement under a grammar rule and then build an interpreter to interpret the statement.
3. Simple implementation
We use the interpreter pattern to interpret the expression "m+n+p", so that the M, N, and p representing the numbers can be considered as the Terminator, and the "+" operation symbol can be used as a non-terminating symbol.
terminalexpression: Terminator expression that implements the interpretation of Terminator in grammar. Each terminator in the grammar has a specific end-expression corresponding to it.
nonterminalexpression : Non-terminator expression, which implements the interpretation of non-terminator in grammar. The non-terminator expression increases according to the complexity of the logic, in principle each grammar rule corresponds to a non-terminator expression.
An abstract arithmetic operator interpreter
publicabstractclass ArithemticExpression { /** * 抽象的解析方法 * 具体的解析逻辑由具体的子类实现 * * @return 解析得到具体的值 */ publicabstractintinterpreter();}
Digital Interpreter
publicclass NumExpression extends ArithemticExpression{ privateint num; publicNumExpression(int num){ this.num = num; } @Override publicintinterpreter() { return num; }}
operator symbol Interpreter
publicabstractclass OperatorExpression extends ArithemticExpression{ protected ArithemticExpression exp1, exp2; publicOperatorExpression(ArithemticExpression exp1, ArithemticExpression exp2){ this.exp1 = exp1; this.exp2 = exp2; }}
Specific addition operator interpreter
publicclass AdditionExpression extends OperatorExpression{ publicAdditionExpression(ArithemticExpression exp1, ArithemticExpression exp2) { super(exp1, exp2); } @Override publicintinterpreter() { return exp1.interpreter() + exp2.interpreter(); }}
Processing interpreter
Public class Calculator { //Declare a stack stack to store and manipulate all relevant interpreters PrivateStack<arithemticexpression> Mexpstack =NewStack<arithemticexpression> (); Public Calculator(String expression) {//Declare two temporary variables of type arithemticexpression, store operators on both left and right of the digital interpreterArithemticexpression EXP1,EXP2;//Split expression string according to space (e.g. 1 + 2 + 3 + 4)string[] elements = Expression.split (" ");/ * * Iterate through an array of expression elements * / for(inti =0; i < elements.length; i++) {/ * * Determine the operation symbol * / Switch(Elements[i].charat (0)) { Case ' + '://If it is a plus, the interpreter in the stack pops up as the interpreter to the left of the operator symbolEXP1 = Mexpstack.pop ();The next element of an array of operation symbols is constructed as a digital interpreter at the same timeEXP2 =NewNumexpression (Integer.parseint (elements[++i));//Construct addition operation interpreter through the above two number interpreterMexpstack.push (NewAdditionexpression (EXP1, EXP2)); Break;default:/ * * If number, construct the digital interpreter directly and press the stack * /Mexpstack.push (NewNumexpression (integer.valueof (elements[i))); Break; } } }/** * Calculation results * * @return Final calculation */ Public int Calculate(){returnMexpstack.pop (). Interpreter (); }}
Call
publicclass Client { publicstaticvoidmain(String[] args) { new Calculator("22 + 553 + 83 + 5"); System.out.println("计算结果:"+c.calculate()); }}
Results:
计算结果:663
If you add operations such as subtraction, add the appropriate judgment to the calculator:
publicclass SubtractionExpression extends OperatorExpression{ publicSubtractionExpression(ArithemticExpression exp1, ArithemticExpression exp2) { super(exp1, exp2); } @Override publicintinterpreter() { return exp1.interpreter() - exp2.interpreter(); }}
Calculator add:
case‘-‘: exp1 = mExpStack.pop(); new NumExpression(Integer.parseInt(elements[++i])); mExpStack.push(new SubtractionExpression(exp1, exp2)); break;
From the above you can see that the interpreter mode is very flexible, he will be complex problems can be simplified, modular, separate implementation, interpretation and execution.
4.Android mode in the source of the implementation of 1.PackageParser
Packageparser is to read the Androidmanifest.xml configuration file, the specific principle of reference: Analysis Androidmanifest principle
5. Summary 1. Advantages
The biggest advantage makes it flexible extensibility, when we want to extend the grammar rules, only need to add the corresponding non-terminator interpreter, and in the construction of abstract syntax tree, using the new interpreter object for specific interpretation can be very convenient.
2. Disadvantages
1. Each syntax to produce a non-terminator expression, grammar rules are more complex, it is possible to generate a large number of class files, maintenance caused a lot of trouble.
2. The interpreter pattern because of the large number of loops and recursion, efficiency is a problem, especially when it comes to parsing complex, lengthy grammars.
6. Reference
Reference Link: Interpreter mode
"Android source design mode analysis and actual combat" reading notes (10)