设计模式之解释器模式22
背景
当我们需要计算a+b-c时,我们需要第一步,定义这个表达式,赋予其逻辑。然后将变量填充,得出结果。我们现在用程序来理解它。
类图
代码实现
表达式的抽象类
public abstract class Expression {
//解析公式与数值,其中var中的key值是公式中的参数,value值是具体的数字
public abstract int interpreter(HashMap<String,Integer> var);
}
变量的类
public class VarExpression extends Expression{
private String key;
public VarExpression(String _key) {
this.key = _key;
}
@Override
public int interpreter(HashMap<String, Integer> var) {
return var.get(this.key);
}
}
符号抽象类
public abstract class SymbolExpression extends Expression{
protected Expression left;
protected Expression right;
public SymbolExpression(Expression _left, Expression _right) {
this.left = _left;
this.right = _right;
}
}
加号
public class AddExpression extends SymbolExpression{
public AddExpression(Expression _left, Expression _right) {
super(_left, _right);
}
@Override
public int interpreter(HashMap<String, Integer> var) {
return super.left.interpreter(var) + super.right.interpreter(var);
}
}
减号
public class SubExpression extends SymbolExpression{
public SubExpression(Expression _left, Expression _right) {
super(_left, _right);
}
@Override
public int interpreter(HashMap<String, Integer> var) {
return super.left.interpreter(var) - super.right.interpreter(var);
}
}
暴露的API处理类
public class Calculator {
private Expression expression;
public Calculator(String expStr) {
Stack<Expression> stacks = new Stack<Expression>();
char[] charArray = expStr.toCharArray();
Expression left = null;
Expression right = null;
for(int i=0; i<charArray.length; i++) {
switch (charArray[i]) {
case '+':
left = stacks.pop();
right = new VarExpression(String.valueOf(charArray[++i]));
stacks.push(new AddExpression(left, right));
break;
case '-':
left = stacks.pop();
right = new VarExpression(String.valueOf(charArray[++i]));
stacks.push(new SubExpression(left, right));
break;
default:
stacks.push(new VarExpression(String.valueOf(charArray[i])));
}
}
this.expression = stacks.pop();
}
public int run(HashMap<String,Integer> var) {
return this.expression.interpreter(var);
}
}
客户端调用
public class Client {
public static void main(String[] args) {
String expStr = "a+b-c";
HashMap<String,Integer> var = new HashMap<String, Integer>();
var.put("a", 100);
var.put("b", 5);
var.put("c", 10);
Calculator cal = new Calculator(expStr);
System.out.println(cal.run(var));
}
}
运行结果
95