Chapter 5th of the design pattern-interpreter mode (Java implementation)

Source: Internet
Author: User

Chapter 5th of the design pattern-interpreter mode (Java implementation)

  "Open a shop good trouble, do a system of receiving orders, found that the methods of the class are many." "Really, is not simple arithmetic, this will not!" "You said you would." Come on, you write the following method in code:

    • A+b+c+d
    • A+b-c
    • A-b+c
    • A+b
    • A-e

、、、

This is the simplest of some of the store's systems, of course, it only contains the addition and subtraction, this time will need me-interpreter.

Self introduction of Interpreter mode

When you are given a language, define a representation of its grammar and define an interpreter to interpret the sentences in the language. Simply speaking, the solution is to parse according to the prescribed syntax, which is less used in current projects. My definition is as follows: Given a language,define a representation for it grammar along with an interpreter that uses the representation T o interpret sentences in the language. Meaning: Given a language, define a representation of its grammar and define an interpreter that uses that representation to interpret sentences in the language. The generic class diagram looks like this:

  

    • Abstractexpression-----An abstract expression

The specific interpretation task is completed by each implementation class, and the specific interpreter is completed by Terminalexpression and Noterminalexpression.

    • Terminalexpression----Terminator Expressions

Implements an interpretation operation associated with an element in the grammar. There is usually only one terminator expression in an interpreter pattern, but there are multiple instances in order to correspond to multiple terminator.

    • noterminalexpression--Non-Terminator expression

Each rule in the grammar corresponds to a non-terminator expression, and each symbol needs to maintain an instance variable of type abstractexpression. And the interpretation operation is implemented for non-terminator in grammar.

    • Context---contexts

Contains some global information outside the interpreter.

    • Client---Customer

Constructs an abstract syntax tree that represents a specific sentence in the language defined by the grammar, and can invoke an interpretation operation.

Self-analysis of the Interpreter method

Well, my shortcomings are not generally more:

    • Will cause the expansion of the class, each syntax to produce a non-terminator expression, syntax rules are more complex, may produce a large number of class files, not easy to maintain.
    • Recursive invocation methods lead to more complex debugging.
    • As a result of using a lot of loops and recursion, the efficiency is naturally lower.

Advantages:

    • Extensibility is good, modify the grammar rules as long as the corresponding non-terminator expression can be modified, if the extension of the syntax, as long as the addition of non-Terminator class.

The implementation of the interpreter

Do you make it concrete? Then I'll take the simple addition and subtraction to make a chestnut.

The Abstractexpression abstract class is as follows:

1  Public Abstract class expression{2     // parse formulas and values, where the key value in Var is the parameter in the formula, and value is the specific number 3      Public Abstract int Interpreter (hashmap<string,integer> var); 4 }

Abstract class is very simple, a method interpreter is responsible for passing in the parameters and values to parse and match, where the input parameter is the HashMap type, the key value is the parameter in the model, such as a, B, C, etc., value is the specific number obtained when the operation. The variable parser code is as follows:

1  Public classVarexpressionextendsexpression{2     PrivateString key;3      Publicvarexpression (String key) {4          This. Key =key;5     }6 7     //take the key from the map8      Public intInterpreter (Hashmap<string, intrger>var) {9         returnVar.get ( This. key);Ten     } One}
View Code

The abstract class of the operation symbol is as follows: 

1  Public Abstract classSymbolexpressionextendsexpression{2     protectedExpression left;3     protectedExpression right;4 5     //you should only care about the Terminator on both sides of the resolution.6      Publicsymbolexpression (expression left, expression right) {7          This. left =Left ;8          This. right =Right ;9     }Ten}
View Code

Parsing, each non-terminator, that is, the operator and the left and right sides of the Terminator, here is the number has a relationship, but two numbers may be an analytic result, no matter what kind, is the implementation of expression class, so in the subclass of operator Resolution added a constructor function, Passing the left and right two expressions, the specific addition subtraction parser is as follows:

Addition Parser:

1  Public classAddexpressionextendssymbolexpression{2      Publicaddexpression (expression left, expression right) {3         Super(left, right);4     }5 6     //Add the left and right two numbers together.7      Public intInterpreter (Hashmap<string, intrger>var) {8         return Super. Left.interpreter (Var) +Super. Right.interpreter (Var);9     }Ten}
View Code

Subtraction parser:

1  Public classsubexpressionextendssymbolexpression{2      Publicsubexpression (expression left, expression right) {3         Super(left, right);4     }5 6     //subtract the left and right two numbers7      Public intInterpreter (Hashmap<string, intrger>var) {8         return Super. Left.interpreter (Var)-Super. Right.interpreter (Var);9     }Ten}
View Code

  At this point, the interpreter is complete, and to expand the multiplication you can see that a simple implementation class is available.

The application scenario of the Interpreter

As for the application scenario, when a language needs to be interpreted and executed, and you can represent the sentence in that language as an abstract syntax tree, you can use that pattern, and it works best when you encounter the following situations:

    • The grammar is relatively simple. Because of the complexity of grammar, the grammatical hierarchy becomes large and cannot be managed.
    • Efficiency is not the key to this issue.

Above. What to know, and listen to tell.

  

PS: This blog welcome forwarding, but please specify the blog address and author ~

Blog Address: http://www.cnblogs.com/voidy/

Blog: http://voidy.gitcafe.com

<. ))) ≦

Chapter 5th of the design pattern-interpreter mode (Java implementation)

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.