通过解释一些简单的加减乘除表达式来演示解释器模式的使用:
首先,我们定义抽象表达式接口:
代码语言:javascript复制public interface Expression {
int interpret(Context context);
}
其中,interpret
方法接收一个上下文环境对象,并根据环境变量进行解释操作。
然后,我们定义终结符表达式类:
代码语言:javascript复制public class NumberExpression implements Expression {
private int number;
public NumberExpression(int number) {
this.number = number;
}
@Override
public int interpret(Context context) {
return number;
}
}
NumberExpression
表示一个数字,它的 interpret
方法直接返回该数字。
接下来,我们定义非终结符表达式类:
代码语言:javascript复制public class AddExpression implements Expression {
private Expression leftExpression;
private Expression rightExpression;
public AddExpression(Expression leftExpression, Expression rightExpression) {
this.leftExpression = leftExpression;
this.rightExpression = rightExpression;
}
@Override
public int interpret(Context context) {
return leftExpression.interpret(context) rightExpression.interpret(context);
}
}
public class SubtractExpression implements Expression {
private Expression leftExpression;
private Expression rightExpression;
public SubtractExpression(Expression leftExpression, Expression rightExpression) {
this.leftExpression = leftExpression;
this.rightExpression = rightExpression;
}
@Override
public int interpret(Context context) {
return leftExpression.interpret(context) - rightExpression.interpret(context);
}
}
public class MultiplyExpression implements Expression {
private Expression leftExpression;
private Expression rightExpression;
public MultiplyExpression(Expression leftExpression, Expression rightExpression) {
this.leftExpression = leftExpression;
this.rightExpression = rightExpression;
}
@Override
public int interpret(Context context) {
return leftExpression.interpret(context) * rightExpression.interpret(context);
}
}
public class DivideExpression implements Expression {
private Expression leftExpression;
private Expression rightExpression;
public DivideExpression(Expression leftExpression, Expression rightExpression) {
this.leftExpression = leftExpression;
this.rightExpression = rightExpression;
}
@Override
public int interpret(Context context) {
return leftExpression.interpret(context) / rightExpression.interpret(context);
}
}
非终结符表达式类实现了 Expression
接口,并包含两个子表达式对象,用于计算表达式的结果。