JavaScript's 23 design patterns of 23 interpreter patterns

JavaScript's 23 design patterns of 23 interpreter patterns

Concept and characteristics

Concept: The
interpreter mode refers to the definition of a language for the analysis object and the definition of the grammatical representation of the language. Then design an interpreter to explain the sentence in the sentence. Use the compiled language to analyze the examples in the application.

Features:

  1. Good scalability. Because classes are used to represent the grammar rules of the language in the interpreter mode, the grammar can be changed or extended through mechanisms such as inheritance.
  2. easy to accomplish. Each expression node class in the syntax tree is similar, so it is easier to implement its grammar.
  3. The execution efficiency is low. The interpreter mode usually uses a large number of loops and recursive calls. When the sentence to be interpreted is more complicated, its running speed is very slow, and the code debugging process is also more troublesome.
  4. Will cause class expansion. Each rule in the interpreter mode needs to define at least one class. When there are many grammatical rules included, the number of classes will increase sharply, making the system difficult to manage and maintain.

Structure and realization

Structure: The
interpreter mode includes [Abstract expression], [Terminal expression], [Non-terminal expression], [Environment] and [Client].
[Abstract expression]: Define the interface of the interpreter and agree on the interpretation operation of the interpreter.
[Terminal expression]: A subclass of abstract expressions used to implement operations related to terminal symbols in the grammar. Each terminal symbol in the grammar has a specific terminal expression corresponding to it.
[Non-terminal symbol expression]: It is also a subclass of abstract expressions, used to implement operations related to non-terminal symbols in the grammar. Each non-terminal symbol in the grammar corresponds to a specific terminal symbol expression.
[Environment]: usually contains data or public functions required by each interpreter. It is generally used to transfer data shared by all interpreters, and subsequent interpreters can obtain these values ​​from here.
[Client]: Convert the sentence or expression that needs to be analyzed into an abstract syntax tree described by the interpreter object, and then call the interpretation method of the interpreter, or indirectly access the interpretation method of the interpreter through the environment role.

Case :
Function description: If the “Shaoyuetong” bus card reader can determine the identity of passengers, if it is “shaoguan” or “Guangzhou” “elderly”, “women” and “children”, they can ride for free, and other people can take the bus for free. The car is deducted 2 yuan at a time.
Please implement the above functions.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    //抽象表达式类
    class Expression{
    
    
        interpret(info){
    
    }
    }
    //终结符表达式
    class TerminalExpression extends Expression{
    
    
        constructor(data){
    
    
            super(data);
            this.set = new Set(data);           
        }
        interpret(info){
    
    
           if(this.set.has(info)){
    
    
              return true
           }else {
    
    
              return false
           }
        }
    }
    //非终结符表达式
    class AndExpression extends Expression{
    
    
        constructor(city,person){
    
    
            super();
            this.city = city;
            this.person = person;
        }
        interpret(info){
    
    
           let s = info.split('的');
           return this.city.interpret(s[0])&&this.person.interpret(s[1])
        }
    }
    //环境
    class Context {
    
    
        constructor() {
    
    
          //定义终结表达式实例和非终结表达式实例
            let citys = ["韶关", "广州"];
            let persons = ["老人", "妇女", "儿童"];
            this.city = new TerminalExpression(citys);
            this.person = new TerminalExpression(persons);
            this.cityPerson = new AndExpression(this.city, this.person);
        }
         //根据非终结表达式实例的解释方法做出反应
        action(info) {
    
    
            let ok = this.cityPerson.interpret(info);
            if (ok) {
    
    
                console.log("您是" + info + ",您本次乘车免费!")
            } else {
    
    
                console.log(info + ",您不是免费人员,本次乘车扣费2元!")
            }
        }
    }
    class Customer{
    
    
        static main(){
    
    
            let bus = new Context();
            bus.action("韶关的老人");
            bus.action("韶关的年轻人");
            bus.action("广州的妇女");
            bus.action("广州的儿童");
            bus.action("山东的儿童");
        }
    }
    Customer.main();
</script>
</body>
</html>

Application scenario

  1. When the grammar of the language is relatively simple, and execution efficiency is not a key issue.
  2. When the problem recurs and can be expressed in a simple language.
  3. When a language needs to be interpreted and executed, and the sentences in the language can be expressed as an abstract syntax tree, such as XML document interpretation.

Applications

Refer to the above case.

to sum up

The interpreter mode applies to the familiar abstract syntax tree and some JSX-like syntax.
[Terminal expression]:
1. Receive and store the matching object.
2. Provide the interpret method to determine whether the object is in the matching object.

[Non-terminal expression]:
1. Receive and store the incoming object.
2. Provide the interpret method. In this method, the incoming object is intercepted and the interpret method of [terminal expression] is called to determine whether the object is in the matching object.

[Environment]:
1. Provide incoming objects,
2. Instantiate and store [terminal symbol expression] and [non-terminal symbol expression],
3. provide action method. In this method, the interpret method of [non-terminal symbol expression] is called to determine whether the object is in the matching object and then react.

Guess you like

Origin blog.csdn.net/weixin_44135121/article/details/106017682