Design pattern (behavioral) interpreter mode (interpreter pattern)

Source: Internet
Author: User
Tags mul

PS One sentence: Eventually choose Csdn to organize the publication of the knowledge points of these years, the article parallel migration to CSDN. Because CSDN also support markdown grammar, Ah!

"Craftsman Joshui Http://blog.csdn.net/yanbober" read the previous "pattern of design (behavioral) visitor pattern (Visitor pattern)" Http://blog.csdn.net/yanbober/article /details/45536787

Overview

The interpreter pattern is the behavior pattern of the class. Given a language, the interpreter pattern can define a representation of its grammar and provide an interpreter at the same time. The client can use this interpreter to interpret the sentences in the language.

Core

Concept: define the grammar of a language and create an interpreter to interpret the sentences in that language, where "language" refers to code that uses the prescribed format and syntax. The interpreter pattern is a class-behaving pattern.

Interpreter mode structure important core modules:

Abstract expressions (expression)

Declares an abstract interface that all of the specific expression roles need to implement. This interface is primarily a interpret () method, which is called an interpretation operation.

Terminator Expressions (Terminal expression)

Implements the interface required by the abstract expression role, mainly a interpret () method; each terminator in the grammar has a specific terminating expression corresponding to it. For example, there is a simple formula R=R1+R2, in which R1 and R2 are terminator, corresponding parsing R1 and R2 of the interpreter is the Terminator expression.

Non-terminator expressions (nonterminal expression)

Each rule in the grammar requires a specific non-terminator expression, the non-terminator expression is generally the operator in the grammar or other keywords, such as the formula R=R1+R2, "+" is non-terminator, parsing "+" of the interpreter is a non-terminator expression.

Environment (context) role

The role of the task is generally used to store the grammar of each terminator corresponding to the specific values, such as R=R1+R2, we give R1 value 100, to R2 assignment value 200. This information needs to be stored in the environment role, and in many cases it is sufficient for us to use map to act as an environment role.

Usage Scenarios

There is a simple syntax rule, such as an SQL statement, that can be interpreted using the interpreter pattern if we need to make RM conversions based on SQL statements.

Some recurring problems, such as subtraction arithmetic, but the formula each time is different, sometimes a+b-c*d, sometimes a*b+c-d, and so on, the formula is changeable, but all are from subtraction four non-terminator to connect, then we can use the interpreter mode.

The interpreter pattern is rarely used in real-world system development because he can cause problems such as efficiency, performance, and maintenance.

Program Ape Instance

The following example simply simulates the subtraction integer arithmetic operation, using the interpreter pattern and not doing too much explanation:

 PackageYanbober.github.io;ImportJava.util.HashMap;ImportJava.util.Map;//Abstract expressions (expression)Interface Expression {intInterpret (context context);}//Terminator expressions (Terminal expression)Class Constant implements Expression {Private intI Public Constant(inti) { This. i = i; }@Override     Public int interpret(Context context) {returnI }}class Variable implements Expression {@Override     Public int interpret(Context context) {returnContext. LookupValue ( This); }}//non-terminator expressions (nonterminal expression)Class Add implements Expression {PrivateExpression left, right; Public ADD(expression left, expression right) { This. left = left; This. right = right; }@Override     Public int interpret(Context context) {returnLeft.interpret (context) + Right.interpret (context); }}class Sub implements Expression {PrivateExpression left, right; Public Sub(expression left, expression right) { This. left = left; This. right = right; }@Override     Public int interpret(Context context) {returnLeft.interpret (context)-right.interpret (context); }}class Mul implements Expression {PrivateExpression left, right; Public Mul(expression left, expression right) { This. left = left; This. right = right; }@Override     Public int interpret(Context context) {returnLeft.interpret (context) * Right.interpret (context); }}class Div implements Expression {PrivateExpression left, right; Public Div(expression left, expression right) { This. left = left; This. right = right; }@Override     Public int interpret(Context context) {returnLeft.interpret (context)/right.interpret (context); }}//environment (context) roleClass Context {PrivateMap ValueMap =NewHashmap<> (); Public void AddValue(Variable x,intY) {valuemap.put (x, y); } Public int LookupValue(Variable x) {return(int) valuemap.get (x); }}//Client Public  class Main {     Public Static void Main(string[] args) {//(A*B)/(a-b+15000)Context context =NewContext (); Variable A =NewVariable (); Variable B =NewVariable (); Constant C =NewConstant (15000); Context.addvalue (A, -); Context.addvalue (b,10000); Expression expression =NewDiv (NewMul (A, B),NewADD (NewSub (A, B), c)); System.out.println ("Result ="+expression.interpret (context)); }}
sum up a

Interpreter Mode Advantages:

Easy to change and expand grammar.

Each grammar rule can be represented as a class, so it is easy to implement a simple language.

It is easier to implement grammar. Each expression node class in the abstract syntax tree is implemented in a similar way, and the code for these classes is not particularly complex, and the node class code can be generated automatically by some tools.

It is more convenient to add new explanatory expressions. If the user needs to add a new explanatory expression that only needs to add a new terminator expression or non-Terminator expression class, the original expression class code does not need to be modified to conform to the "open and closed principle".

Interpreter Mode Disadvantage:

Difficult to maintain for complex grammars. In interpreter mode, each rule needs to define at least one class, so if a language contains too many grammatical rules, the number of classes will increase dramatically, making the system difficult to manage and maintain, and consider using a parser to replace the interpreter pattern.

less efficient execution. Because of the large number of loops and recursive calls in the interpreter pattern, it is slow to interpret more complex sentences, and the code debugging process is cumbersome.

"Artisan Joshui Http://blog.csdn.net/yanbober"

Design pattern (behavioral) interpreter mode (interpreter pattern)

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.