Interpreter mode

The Interpreter Pattern, which provides a way to evaluate the syntax or expressions of a language, is a behavioral Pattern.

This pattern implements an expression interface that interprets a particular context. This pattern is often used in Babel, Sass, less parsing, symbol processing engines, and so on.

intentions

Given a language, define its grammatical representation and define an interpreter that uses the identifier to interpret sentences in the language.

For example, the regular expression we often use in development is an application of the interpreter pattern. The interpreter will interpret a regular expression according to the fixed grammar of the regular expression.

scenario

If a particular type of problem occurs frequently enough, it may be worth expressing individual instances of the problem as a sentence in a simple language. This allows you to build an interpreter that solves the problem by interpreting the sentences

  1. A sentence in a language that needs to be interpreted can be represented as an abstract syntax tree.
  2. Some recurring problems can be expressed in a simple language;
  3. A scenario where simple syntax needs to be explained

advantages

  1. Good scalability
  2. Flexibility is high
  3. Easy to implement simple grammars

disadvantages

  1. There are fewer scenarios available
  2. Parsers for complex grammars are difficult to maintain
  3. The interpreter pattern causes class bloat
  4. The interpreter mode uses a large number of recursive and circular invocation methods, which are inefficient and consume high performance

The sample code

We define a TerminalExpression class that acts as the main interpreter in the context. Other classes OrExpression and AndExpression are used to create combinative expressions.

Class TerminalExpression {constructor(data) {this.data = data} interpret(context) { If (context.includes(context)){return true} return false}} class OrExpression {constructor(expr1, expr2) { this.expr1 = expr1 this.expr2 = expr2 } interpret(context) { return this.expr1.interpret(context) || This. Expr2. interpret(context)}} // Constructor (expr1, expr2) { this.expr1 = expr1 this.expr2 = expr2 } interpret(context) { return this.expr1.interpret(context) && this.expr2.interpret(context) } } const robert = new TerminalExpression('Robert') const john = new TerminalExpression('John') const isMale = new OrExpression(robert, john) const julie = new TerminalExpression('Julie') const married = new TerminalExpression('Married ') const isMarriedWoman = new AndExpression(julie, married) console.log(`John is male ? ${isMale.interpret('john')}`) // John is male ? true console.log(`Julie is a married women ? ${isMarriedWoman.interpret('Married Julie')}`) // Julie is a married women ? trueCopy the code