Interpreter Mode Overview
Given a language, it defines a representation of its syntax and an interpreter that uses this representation to interpret sentences in the language.
Applicability
When a language needs to be interpreted and executed, and you can represent sentences in the language as an abstract syntax tree, you can use the interpreter mode. In the following cases, this mode has the best effect: 1. This grammar is simple for complex grammar, and the class level of grammar becomes huge and cannot be managed. 2. efficiency is not a key issue. The most efficient interpreter is usually not implemented by directly interpreting the syntax analysis tree, but first converts them into another form.
Participants
1. abstractexpression (Abstract Expression) declares an abstract interpretation operation, which is shared by all nodes in the abstract syntax tree. 2. terminalexpression (Terminator expression) implements interpretation operations associated with Terminators in grammar. Each terminator in a sentence needs an instance of this class. 3. nonterminalexpression (non-terminator expression) is a non-terminator in grammar to implement an interpretation (interpret) operation. 4. Context contains some global information except the interpreter. 5. The client (customer) constructs (or is given) the abstract syntax tree of a specific sentence in the language defined by the syntax. The abstract syntax tree is composed of nonterminalexpression and terminalexpression instances. Call the explain operation.
Example
Abstractexpression public abstract class expression {abstract void interpret (context CTX);} expression public class advanceexpression extends expression {void interpret (context CTX) {system. out. println ("This is an advanced parser! ") ;}} Public class simpleexpression extends expression {void interpret (context CTX) {system. Out. println (" this is a common parser! ") ;}} Context public class context {private string content; private list = new arraylist (); Public void setcontent (string content) {This. content = content;} Public String getcontent () {return this. content;} public void add (expression EPS) {list. add (EPS) ;}public list getlist () {return list ;}} test public class test {public static void main (string [] ARGs) {context CTX = new context (); CTX. add (New simpleexpression (); CTX. add (New advanceexpression (); CTX. add (New simpleexpression (); For (expression EPS: CTX. getlist () {EPS. interpret (CTX) ;}} result this is a common parser! This is an advanced parser! This is a common parser!