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
- A sentence 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
advantages
- Good scalability
- Flexibility is high
- Easy to implement simple grammars
disadvantages
- There are fewer scenarios available
- Parsers for complex grammars are difficult to maintain
- The interpreter pattern causes class bloat
- 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