The interpreter pattern (interpreter), given a language, defines a representation of its grammar, and defines an interpreter that uses that representation to interpret sentences in the language.
If a particular type of problem occurs at a sufficiently high frequency, it might be worthwhile to describe each instance of the problem as a sentence in a simple language. This allows you to build an interpreter that solves the problem by interpreting these sentences.
The so-called interpreter pattern, the regular expression is one of its applications, the interpreter defines a grammar for a regular expression, how to represent a particular regular expression, and how to interpret the regular expression.
In general, you can use the interpreter pattern when there is a language that needs to be interpreted and executed, and you can represent sentences in that language as an abstract syntax tree.
The benefit of the interpreter pattern: it is easy to change and extend the grammar, because it uses classes to represent grammar rules, and you can use inheritance to change or extend the grammar. It is also easier to implement grammars because the classes that define the individual nodes in the abstract syntax tree are broadly similar in their implementation, and are easy to write directly.
Deficiency: The interpreter pattern defines at least one class for each rule in the grammar, so grammars that contain many rules can be difficult to manage and maintain. It is recommended to use other techniques, such as a parser or compiler builder, when the grammar is very complex.
Demo:
classContext {Private stringinput; Public stringInput {Get{returninput;} Set{input =value;} } Private stringoutput; Public stringOutput {Get{returnoutput;} Set{output =value;} } }
Abstract class abstractexpression { publicabstractvoid interpret (context context); }
class terminalexpression: abstractexpression { public override
void interpret (context context) { Console.WriteLine ( terminal interpreter " ); } }
class nonterminalexpression:abstractexpression { publicoverridevoid interpret (context context) { Console.WriteLine (" non-terminal interpreter "); } }
Test:
New Context (); IListNew list<abstractexpression>(); Expressions. ADD (new terminalexpression ()); Expressions. ADD (new nonterminalexpression ()); Expressions. ADD (new terminalexpression ()); foreach (var in expressions) { item. Interpret (context); }
Notes-Liar design mode-27 interpreter mode