Structure |
|
Intention |
Given a language, define a representation of its grammar and define an interpreter that interprets the sentences in the language using that representation. |
Applicability |
- You can use the interpreter pattern when there is a language that needs to be interpreted and executed, and you can represent a sentence in that language as an abstract syntax tree. This mode works best when the following conditions are present:
- The grammar is simple for complex grammars, and the class hierarchy of grammars becomes large and cannot be managed. Tools such as the parser generator are a better choice at this point. They can explain expressions without building an abstract syntax tree, which saves space and can save time.
- Efficiency is not a key issue the most efficient interpreters are usually not implemented by directly interpreting the parse tree, but rather first converting them to another form. For example, regular expressions are often converted to state machines. However, even in this case, the converter can still be implemented using the interpreter pattern, which is still useful.
|
1 usingSystem;2 usingSystem.Collections;3 4 classContext5 {6 7 }8 9 Abstract classabstractexpressionTen { One Abstract Public voidinterpret (Context c); A } - - //class for terminal symbol the classterminalexpression:abstractexpression - { - Override Public voidinterpret (Context c) - { + - } + } A at //Class for grammar rule (one per rule needed) - classnonterminalexpression:abstractexpression - { - Override Public voidinterpret (Context c) - { - in } - } to //to extend grammar, just add other nonterminalexpression classes + - /// <summary> the ///Summary description for Client. * /// </summary> $ Public classClientPanax Notoginseng { - Public Static intMain (string[] args) the { +Context C =NewContext (); AArrayList L =NewArrayList ();//really need a tree here! the + //build up context information - // . . . $ $ //Populate Abstract syntax tree with data -L.add (Newterminalexpression ()); -L.add (Newnonterminalexpression ()); the - //interpretWuyi foreach(Abstractexpression expinchl) the { - exp. Interpret (c); Wu } - About return 0; $ } -}
Interpreter Mode
Interpreter mode for behavioral design patterns (interpreter)