An introduction to the Interpreter pattern of the Java design pattern
- 2020-04-01 03:42:17
- OfStack
Interpreter definition: defines the grammar of a language and sets up an Interpreter to interpret the sentences in that language.
Interpreter does not seem to be widely used. It describes how a language Interpreter is constructed. In practice, we may seldom construct the grammar of a language. So let's take a quick look.
The first step is to create an interface to describe common operations.
public interface AbstractExpression {
void interpret( Context context );
}
Now let's look at some global information that contains outside of the interpreter
public interface Context { }
AbstractExpression There are two kinds of realization: terminal expression and non-terminal expression.
public class TerminalExpression implements AbstractExpression {
public void interpret( Context context ) { }
}
For no rule in grammar, non-terminal expressions are required:
public class NonterminalExpression implements AbstractExpression {
private AbstractExpression successor;
public void setSuccessor( AbstractExpression successor ) {
this.successor = successor;
}
public AbstractExpression getSuccessor() {
return successor;
}
public void interpret( Context context ) { }
}