"Onlookers" design mode (27)--Behavioral interpreter mode (interpreter pattern)

Source: Internet
Author: User

The parser is an example of parsing in accordance with the prescribed syntax, which is used less in the current project, defined as follows: Given a language, define a representation of its grammar, and define an interpreter that interprets the sentences in the language.


Personal Understanding


The interpreter pattern is seldom used in the project because he can cause problems such as efficiency, performance, and maintenance, and when preparing to use the schema, open source frameworks such as expression4j, MESP, Jep, etc. are considered. The interpreter pattern is commonly used to parse a standard set of characters, such as SQL syntax analysis.


Interpreter Role

The interpreter pattern consists mainly of the following roles:

Abstractexpression: An abstract expression. Declares an abstract interpretation operation that is shared by all nodes in the abstract syntax tree.

Terminalexpression: an terminator expression. Implements interpretation operations related to Terminator in the grammar. Implements the method required in an abstract expression. Every terminator in grammar has a specific ending expression corresponding to it.

Nonterminalexpression: Non-terminator expression. A non-terminator-related interpretation operation in the grammar.

Context: Environment class. Contains some global information outside of the interpreter.

Client: Customer class.

Abstract syntax tree describes how to form a complex sentence, through the analysis of the abstract syntax tree, can identify the language of the Terminator and non-Terminator class. In the interpreter mode, because each terminator expression, non-terminator expression will have a specific instance corresponding to it, so the scalability of the system is better.



Case Analysis


An expression that deserves a simple example (drawing on the code in the Zen of design patterns)

Public abstract class Expression {public abstract int interpreter (hashmap<string, integer> var);}

Variable parser

public class Varexpression extends Expression {private string Key;public varexpression (String key) {This.key = key;} @Overridepublic int Interpreter (hashmap<string, integer> var) {int value = Var.get (key); return value;}}

Abstract operator Classes

Public abstract class Symbolexpression extends expression {protected expression left;protected expression Right;public Sy Mbolexpression (expression left, expression right) {This.left = Left;this.right = Right;}}

Addition Parser

public class Addexpression extends Symbolexpression {public addexpression (expression left, expression right) {super (left , right);} @Overridepublic int Interpreter (hashmap<string, integer> var) {///around two expression values add return Super.left.interpreter (VAR) + Super.right.interpreter (var);}}

Subtraction Parser


public class subexpression extends Symbolexpression {public subexpression (expression left, expression right) {super (left , right);} @Overridepublic int Interpreter (hashmap<string, integer> var) {//subtract the values of the left and right two expressions return Super.left.interpreter (var )-Super.right.interpreter (Var);}}

public class Calculator {private Expression expression;public Calculator (String expstr) {stack<expression> Stack = New Stack<expression> (); char[] Chararray = Expstr.tochararray (); Expression left = null; Expression right = null;for (int i = 0; i < chararray.length; i++) {switch (Chararray[i]) {case ' + '://addition, take out the left-hand value, get to the Add and place the result on the stack to save left = Stack.pop (), right = new Varexpression (string.valueof (Chararray[++i])), Stack.push (new Addexpression (left, right)); Break;case '-'://subtraction, take out the value to the right, subtract the value from the side and place the result on the stack save left = Stack.pop. right = new Varexpression (string.valueof (chararray[++i)); Stack.push (new subexpression (left, right)); break;default:// The numbers are saved directly to the stack Stack.push (new Varexpression (String.valueof (chararray[i))); This.expression = Stack.pop ();} public int Run (hashmap<string, integer> var) {return this.expression.interpreter (VAR);}}

Test class

public class Client {public static void main (string[] args) {String expstr = Getexpstr (); Hashmap<string, integer> var = getValue (EXPSTR); Calculator cal = new Calculator (EXPSTR); System.out.println (expstr + "=" + Cal.run (Var));} private static hashmap<string, integer> GetValue (String expstr) {hashmap<string, integer> map = new HASHMAP&L T String, integer> (), for (Char Ch:expStr.toCharArray ()) {if (ch! = ' + ' && ch! = '-') {if (!map.containskey (String . VALUEOF (CH)) {System.out.println ("the symbol in the input expression" + ch + "represents the value:"); Scanner Scanner = new Scanner (system.in); int num = Scanner.nextint (); Map.put (string.valueof (CH), num);}}} return map;} private static String Getexpstr () {System.out.println ("Input expression:"); Scanner Scanner = new Scanner (system.in); return Scanner.nextline ();}}


advantages of the interpreter

1, scalability is better, flexible.

2. Added a new way to interpret expressions.

3, easy to implement grammar.


the drawbacks of the interpreter

1, the execution efficiency is low, the available scene is relatively small.

2, for complex grammar is difficult to maintain.



application scenarios for the interpreter

1. A sentence in a language that needs to be interpreted for execution can be represented as an abstract syntax tree.

2. Some recurring problems can be expressed in a simple language.

3, grammar is relatively simple.


design Pattern Source code

Design mode source code



"Onlookers" design mode (27)--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.