概述
- 定义:定义一个语言的文法,并且建立一个解释器来解释该语言中的句子,这里的“语言”是指使用规定格式和语法的代码。
- 解释器模式是一种类行为型模式。
- 学习难度:★★★★★
- 使用频率:★☆☆☆☆
优缺点
- 优点
- 提供了一个简单的方式来执行语法,而且容易修改或者扩展语法。
- 缺点
类图
组成角色
- 抽象解析器角色(AbstractExpression)
- 终结符表达式(TerminalExpression)
- 非终结符表达式(NonterminalExpression)
- 环境角色(Context)
Code Example
抽象解析器角色(AbstractExpression)
public interface Expression {
public Integer interpret(Context ctx);
}
终结符表达式(TerminalExpression)
public class Variable implements Expression {
public Integer interpret(Context ctx) {
return ctx.get(this);
}
}
public class Constant implements Expression {
private Integer i;
public Constant(Integer i) {
this.i = i;
}
public Integer interpret(Context ctx) {
return i;
}
}
非终结符表达式(NonterminalExpression)
public class Add implements Expression {
private Expression left, right;
public Add(Expression left, Expression right) {
this.left = left;
this.right = right;
}
public Integer interpret(Context ctx) {
return left.interpret(ctx) + right.interpret(ctx);
}
}
class Subtract implements Expression {
private Expression left, right;
public Subtract(Expression left, Expression right) {
this.left = left;
this.right = right;
}
public Integer interpret(Context ctx) {
return left.interpret(ctx) - right.interpret(ctx);
}
}
public class Multiply implements Expression {
private Expression left, right;
public Multiply(Expression left, Expression right) {
this.left = left;
this.right = right;
}
public Integer interpret(Context con) {
return left.interpret(con) * right.interpret(con);
}
}
public class Division implements Expression {
private Expression left, right;
public Division(Expression left, Expression right) {
this.left = left;
this.right = right;
}
public Integer interpret(Context con) {
try {
return left.interpret(con) / right.interpret(con);
} catch (ArithmeticException ae) {
System.out.println("被除数为0!");
return -11111;
}
}
}
环境角色(Context)
public class Context {
private Map<Variable, Integer> valueMap = new HashMap<Variable, Integer>();
public void addValue(Variable x, Integer y) {
valueMap.put(x, y);
}
public Integer get(Variable x) {
Integer i = valueMap.get(x);
return i;
}
}
客户端
public class InterpreterPattern {
public static void main(String[] args) {
Context ctx = new Context();
Variable a = new Variable();
Variable b = new Variable();
Constant c = new Constant(2);
ctx.addValue(a, 6);
ctx.addValue(b, 7);
Expression exp = new Division(new Multiply(a, b), new Add(new Subtract(a, b), c));
System.out.println("运算结果为:" + exp.interpret(ctx));
}
}