Use
Interpreter mode (interpreter)
Defines a language that defines a representation of its grammar.
and defines an interpreter that uses that representation to interpret sentences in the language.
The interpreter pattern is a behavioral pattern .
structure
Figure-Interpreter Mode
Context: contains some global information outside the interpreter.
classContext {
PrivateString input;
PrivateString output;
PublicvoidSetInput (String input) {
This. input = input;
}
PublicString GetInput () {
return This. Input;
}
PublicvoidSetoutput (String output) {
This. output = output;
}
PublicString GetOutput () {
return This. Output;
}
}
abstractexpression: Declares an abstract interpretation operation that is shared by all nodes in the abstract syntax tree.
Abstractclassabstractexpression {
PublicAbstract voidInterpret (context context);
}
terminalexpression: Implements the interpretation operation associated with Terminator in the grammar. Implementing an interface that is required in an abstract expression is primarily a interprete () method.
Each terminator in the grammar has a specific end expression corresponding to it.
classTerminalexpressionextendsabstractexpression {
@Override
PublicvoidInterpret (context context) {
Context.setoutput ("terminal" + context.getinput ());
System.out.println (Context.getinput () + "after the terminal interpreter interpreted as:" + context.getoutput ());
}
}
nonterminalexpression: Implements an interpreted operation associated with a non-terminator in the grammar. The r1,r2 of every rule in grammar ... RN requires a specific non-Terminator expression class. The interpretation operation is implemented by implementing the interpret method of an abstract expression.classNonterminalexpressionextendsabstractexpression {
@Override
Public voidInterpret (context context) {
Context.setoutput ("Non-terminal" + context.getinput ());
System.out.println (Context.getinput () + "after non-terminal interpreter interpreted as:" + context.getoutput ());
}
}
Test code
PublicclassInterpreterpattern {
PublicStatic voidMain (string[] args) {
Context context =NewContext ();
Context.setinput ("ABC");
Abstractexpression expression1 =NewTerminalexpression ();
Expression1. Interpret (context);
Abstractexpression expression2 =NewNonterminalexpression ();
Expression2. Interpret (context);
}
}View Code
Run results
ABC is interpreted by the terminal interpreter as: TERMINAL ABC
ABC is interpreted by non-terminal interpreter as: Non-terminal ABCView Code
JAVA Design Pattern Interpreter mode