说明
- 给定一门语言,定义它的文法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言中的句子。
角色
- 抽象表达式类
- 末端表达式类:数字变量
- 非末端表达式:±操作
- 环境角色:存一些变量。。。
- 客户端
代码实现
public abstract class Expression {
public abstract int interpreter(Map<String,Integer> var);
}
public class VarExpression extends Expression {
private String key;
VarExpression(String key){
this.key = key;
}
@Override
public int interpreter(Map<String, Integer> var) {
return var.get(key);
}
}
public abstract class SymbolExpression extends Expression{
protected Expression left;
protected Expression right;
SymbolExpression(Expression left,Expression right){
this.left = left;
this.right = right;
}
public Expression getLeft() {
return left;
}
public Expression getRight() {
return right;
}
public void setLeft(Expression left) {
this.left = left;
}
public void setRight(Expression right) {
this.right = right;
}
}
public class SubSymbolExpression extends SymbolExpression {
SubSymbolExpression(Expression left, Expression right) {
super(left, right);
}
@Override
public int interpreter(Map<String, Integer> var) {
return super.left.interpreter(var)-super.right.interpreter(var);
}
}
public class AddSymbolExpression extends SymbolExpression {
AddSymbolExpression(Expression left, Expression right) {
super(left, right);
}
@Override
public int interpreter(Map<String, Integer> var) {
return super.left.interpreter(var)+super.right.interpreter(var);
}
}
public class MultiplySymbolExpression extends SymbolExpression{
MultiplySymbolExpression(Expression left, Expression right) {
super(left, right);
}
@Override
public int interpreter(Map<String, Integer> var) {
return super.left.interpreter(var)*super.right.interpreter(var);
}
}
public class Calculate {
private Stack<Expression> stack = new Stack<>();
private Expression result;
private Expression left;
private Expression right;
Calculate(String expression) {
char[] chars = expression.toCharArray();
for (int i = 0; i < chars.length; i++) {
switch (chars[i]) {
case '+':
left = stack.pop();
right = new VarExpression(chars[++i]+"");
stack.push(new AddSymbolExpression(left,right));
break;
case '-':
left = stack.pop();
right = new VarExpression(chars[++i]+"");
stack.push(new SubSymbolExpression(left,right));
break;
case '*':
left = stack.pop();
right = new VarExpression(chars[++i]+"");
if(left instanceof AddSymbolExpression || left instanceof SubSymbolExpression){
((SymbolExpression) left).setRight(new MultiplySymbolExpression(((SymbolExpression) left).getRight(),right));
stack.push(left);
break;
}
stack.push(new MultiplySymbolExpression(left,right));
break;
default:
stack.push(new VarExpression(chars[i]+""));
break;
}
}
result = stack.pop();
}
public int run(Map<String,Integer> var){
return result.interpreter(var);
}
}
public class Test {
public static void main(String[] args){
Calculate calculate = new Calculate("a+b*c");
Map<String,Integer> varMap = new HashMap<>();
varMap.put("a",5);
varMap.put("b",4);
varMap.put("c",1);
System.out.println(calculate.run(varMap));
}
}