Analysis of Android source code design patterns and practices (10)

Source: Internet
Author: User

Analysis of Android source code design patterns and practices (10)
Chapter 10 interpreter Mode

The interpreter mode is a relatively small behavior mode, which provides a syntax or expression method for interpreting languages. However, it is widely used, but it is rarely used because we seldom construct the grammar of a language.

1. Definition

Given a language, it defines a syntax expression and an interpreter that uses this representation to interpret sentences in the language. (Language is the object we need to explain. grammar is the law of this language. The interpreter is a translator who uses grammar to translate the language .)

2. Use Cases

1. IfSimple languageThe interpreter mode can be used to explain and execute the statements in the language as an abstract syntax tree.
2. When repeated problems occur in certain fields, you can convert the problems in this field into statements under a syntax rule, and then build an interpreter to explain the statements.

3. Simple implementation

We use the interpreter mode to interpret the expression "m + n + p". Then, m, n, and p representing numbers can be seen as terminologies, the "+" operator can be used as a non-Terminator.
TerminalExpression: Terminator expression, which is used to explain the terminator in grammar. Each terminator in the grammar has a specific ending expression corresponding to it.
NonterminalExpression: Non-terminator expression, which can be used to explain non-terminator operations in grammar. Non-terminator expressions increase based on the complexity of the logic. In principle, each grammar rule corresponds to a non-terminator expression.

An abstract arithmetic Interpreter

Public abstract class ArithemticExpression {/*** abstract Parsing Method * The specific parsing logic is implemented by the specific subclass ** @ return parsing to obtain the specific value */public abstract int interpreter () ;}

Number Interpreter

public class NumExpression extends ArithemticExpression{    private int num;    public NumExpression(int num){        this.num = num;    }    @Override    public int interpreter() {        return num;    }}

Operator number Interpreter

public abstract class OperatorExpression extends ArithemticExpression{    protected ArithemticExpression exp1, exp2;    public OperatorExpression(ArithemticExpression exp1, ArithemticExpression exp2){        this.exp1 = exp1;        this.exp2 = exp2;    }}

Specific addition operator Interpreter

public class AdditionExpression extends OperatorExpression{    public AdditionExpression(ArithemticExpression exp1,            ArithemticExpression exp2) {        super(exp1, exp2);    }    @Override    public int interpreter() {        return exp1.interpreter() + exp2.interpreter();    }}

Process Interpreter

Public class Calculator {// declare a Stack to store and operate on all relevant interpreters private Stack mExpStack = new Stack (); public Calculator (String expression) {// declare two temporary variables of the ArithemticExpression type, and store the ArithemticExpression exp1 and exp2 on both sides of the operator; // split the expression String by space (for example, 1 + 2 + 3 + 4) String [] elements = expression. split ("");/** traversal expression element array */for (int I = 0; I <elements. length; I ++) {/** judge operator number */switch (elements [I]. charAt (0) {case '+': // if it is a plus sign, the interpreter in the stack will pop up as the interpreter on the left of the operator number exp1 = Mexico stack. pop (); // At the same time, construct the next element under the operator number array as a digital interpreter exp2 = new NumExpression (Integer. parseInt (elements [++ I]); // you can use the preceding two numerical interpreters to construct the addition operator mExpStack. push (new AdditionExpression (exp1, exp2); break; default:/** if it is a number, directly construct a digital interpreter and press it into the stack */mExpStack. push (new NumExpression (Integer. valueOf (elements [I]); break ;}}/ ***** calculation result ** @ return final calculation result */public int calculate () {return mExpStack. pop (). interpreter ();}}

Call

Public class Client {public static void main (String [] args) {Calculator c = new Calculator ("22 + 553 + 83 + 5"); System. out. println ("Calculation Result:" + c. calculate ());}}

Result:

Calculation Result: 663

If the addition is a subtraction operation, add the corresponding judgment to Calculator:

public class SubtractionExpression extends OperatorExpression{    public SubtractionExpression(ArithemticExpression exp1,            ArithemticExpression exp2) {        super(exp1, exp2);    }    @Override    public int interpreter() {        return exp1.interpreter() - exp2.interpreter();    }}

Add the following to Calculator:

case '-':    exp1 = mExpStack.pop();    exp2 = new NumExpression(Integer.parseInt(elements[++i]));    mExpStack.push(new SubtractionExpression(exp1, exp2));    break;

It can be seen from the above that the interpreter mode is flexible. He can simplify complicated problems, modularize, implement separation, and explain execution.

4. Implementation of the pattern in the Android Source Code 1. PackageParser

PackageParser reads the AndroidManifest. xml configuration file. For details, refer to: parsing AndroidManifest principles.

5. Summary 1. Advantages

The biggest advantage is its flexible scalability. When we want to extend grammar rules, we only need to add the corresponding non-terminator interpreter and construct the abstract syntax tree, it is very convenient to use the newly added interpreter object for specific explanations.

2. Disadvantages

1. Each syntax generates a non-terminator expression. When syntax rules are complex, a large number of class files may be generated, which brings a lot of trouble to maintenance.
2. Because the interpreter mode uses a lot of loops and recursion, efficiency is a problem. Especially when it is used to parse complex and lengthy syntaxes, efficiency is intolerable.

6. Reference

Reference link: Explanation of interpreter Mode

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.