This is the 15th day of my participation in the August Text Challenge.More challenges in August


I want to learn the interpreter pattern of design patterns

Interpreter pattern: provides a way to evaluate the syntax or expressions of a language.


What is “interpreter mode”?

Interpreter schema definition: provides a way to evaluate a language’s syntax or expression. This is a design pattern that is rarely used. I can’t think of a scenario that would necessarily use this design pattern.

The key to implementing this pattern is:

  1. Abstract expressions: There is mainly a interpret() operation

    • Terminal expression:R = R1 + R2,R1 R2That’s the terminal
    • Non-terminal expressions:R = R1 - R2,-That’s the terminal
  1. Environment (Context) :storeIn grammarterminatorThat corresponds to a specific value. Such as the frontR1andR2The value of the.

The advantages and disadvantages

Advantages:

  1. Good scalability and flexibility.
  2. Added new ways to interpret expressions, making it easy to implement simple grammars.

Disadvantages:

  1. There are fewer scenarios available.
  2. Complex grammars are difficult to maintain.
  3. The interpreter pattern causes class bloat and is difficult to maintain
  4. The interpreter mode uses recursive invocation methods, and the execution of statements is inefficient

Usage scenarios

Sentences in a language that needs to be interpreted can be represented as an abstract syntax tree. Some recurring problems can be expressed in a simple language. A scenario where simple syntax needs to be explained. Examples are: compiler, operation expression calculation, regular expression


Code implementation

The implementation of the “abstract expression” is omitted for convenience.

class Context { constructor() { this._list = []; This. _sum = 0; } get sum() {return this._sum; } set sum(newValue) { this._sum = newValue; } add(expression) { this._list.push(expression); } get list() { return [...this._list]; } } class PlusExpression { interpret(context) { if (! (context instanceof Context)) { throw new Error("TypeError"); } context.sum = ++context.sum; } } class MinusExpression { interpret(context) { if (! (context instanceof Context)) { throw new Error("TypeError"); } context.sum = --context.sum; **/ const context = new context (); / / in turn add: addition | | addition subtraction expression context. The add (new PlusExpression ()); context.add(new PlusExpression()); context.add(new MinusExpression()); / / in sequence: addition | | addition subtraction expression context. The list. The forEach (expression = > expression. Interpret (context)); console.log(context.sum);Copy the code