Java Implementation Interpreter Pattern
Interpreter Pattern is a behavior design pattern that defines the grammar of a language and defines an interpreter that interprets statements in that language.
This design pattern is applicable to the following scenarios:
When a language needs to be interpreted and executed with scalability, the interpreter mode can be used. For example, a calculator interpreter can parse and execute mathematical expressions.
When the grammar of the language is relatively simple, the interpreter mode can be used. Complex syntax may lead to overly complex implementation of the interpreter.
The benefits of using interpreter mode include:
1. Syntax rules can be expressed as Abstract syntax tree, which is easy to understand and modify.
2. New expressions can be added without modifying the interpreter code.
3. Complex interpreters can be constructed by combining different expressions.
The following is a simple Java sample code that implements a simple calculator interpreter.
//Abstract expression interface
interface Expression {
int interpret();
}
//Terminator expression implementation class
class Number implements Expression {
private int value;
public Number(int value) {
this.value = value;
}
public int interpret() {
return value;
}
}
//Non Terminator Expression Implementation Class
class Add implements Expression {
private Expression left;
private Expression right;
public Add(Expression left, Expression right) {
this.left = left;
this.right = right;
}
public int interpret() {
return left.interpret() + right.interpret();
}
}
//Client code
public class InterpreterPatternDemo {
public static void main(String[] args) {
//Building Abstract syntax tree of Interpreter
Expression expression = new Add(new Number(10), new Add(new Number(5), new Number(3)));
//Interpret Execution Grammar Tree
int result = expression.interpret();
System.out.println("Result: " + result);
}
}
In the above sample code, we defined an abstract expression interface 'Expression' and implemented two concrete expression classes' Number 'and' Address'` The 'Number' class represents numbers, and the 'Add' class represents addition operations. The client code builds a Abstract syntax tree, then executes the syntax tree through the interpreter, and outputs the results.
In this simple calculator interpreter, we only implemented addition operations, but we can extend the interpreter's functionality by implementing new expression classes, such as subtraction, multiplication, and so on. This is a major advantage of the interpreter mode.