
优点 | 缺点 |
|---|---|
1. 灵活扩展语法:新增语法规则只需添加表达式类。 | 1. 类数量膨胀:复杂语法导致大量类。 |
2. 易于实现简单语言:如数学表达式、规则引擎。 | 2. 效率较低:递归解析可能影响性能。 |
3. 可读性强:语法规则与代码结构一一对应。 | 3. 处理复杂文法困难:需结合其他解析技术(如ANTLR)。 |
/**
* 抽象表达式接口:定义 interpret 解释方法
*/
public interface Expression {
int interpret(Context context);
}/**
* 终结符表达式:变量(如 a、b)
*/
public class Variable implements Expression {
private final String name;
public Variable(String name) {
this.name = name;
}
@Override
public int interpret(Context context) {
return context.getValue(this.name);
}
}
/**
* 终结符表达式:数字常量(如 5、10)
*/
public class Number implements Expression {
private final int value;
public Number(int value) {
this.value = value;
}
@Override
public int interpret(Context context) {
return this.value;
}
}/**
* 非终结符表达式:加法运算(如 a + b)
*/
public class Add implements Expression {
private final Expression left;
private final Expression right;
public Add(Expression left, Expression right) {
this.left = left;
this.right = right;
}
@Override
public int interpret(Context context) {
return left.interpret(context) + right.interpret(context);
}
}
/**
* 非终结符表达式:减法运算(如 a - b)
*/
public class Subtract implements Expression {
private final Expression left;
private final Expression right;
public Subtract(Expression left, Expression right) {
this.left = left;
this.right = right;
}
@Override
public int interpret(Context context) {
return left.interpret(context) - right.interpret(context);
}
}import java.util.HashMap;
import java.util.Map;
/**
* 上下文类:存储变量名与值的映射关系
*/
public class Context {
private final Map<String, Integer> variables = new HashMap<>();
// 设置变量值
public void setVariable(String name, int value) {
variables.put(name, value);
}
// 获取变量值
public int getValue(String name) {
Integer value = variables.get(name);
if (value == null) throw new IllegalArgumentException("变量未定义: " + name);
return value;
}
}public class Client {
public static void main(String[] args) {
// 创建上下文并设置变量值
Context context = new Context();
context.setVariable("a", 10);
context.setVariable("b", 5);
// 构建表达式:(a + (b - 2))
Expression expression = new Add(
new Variable("a"),
new Subtract(new Variable("b"), new Number(2))
);
// 解释执行表达式
int result = expression.interpret(context);
System.out.println("计算结果: " + result); // 输出 13
}
}+----------------+ +----------------+
| Expression | <------+ | Context |
+----------------+ +----------------+
| +interpret() | | +getValue() |
+----------------+ +----------------+
^
|
+----------------+
| TerminalExpression |
+----------------+
| +interpret() |
+----------------+
^
|
+----------------+
| NonTerminalExpression |
+----------------+
| -left:Expression |
| -right:Expression |
| +interpret() |
+----------------+ 解释器模式在 Java 生态中的典型应用包括:
java.util.regex.Pattern 解析正则语法。
掌握该模式能为特定领域问题提供高度定制化的解决方案,但需权衡其适用性与复杂度。