设计模式之解释器模式
public class Test6 {/** * @param args */public static void main(String[] args) throws Exception {String expStr = getExpStr();// 赋值HashMap<String, Integer> var = getValue(expStr);Calculator cal = new Calculator(expStr);System.out.println("运算结果为:" + expStr + "=" + cal.run(var));}// 获得表达式public static String getExpStr() throws IOException {System.out.print("请输入表达式:");return (new BufferedReader(new InputStreamReader(System.in))).readLine();}// 获得值映射public static HashMap<String, Integer> getValue(String exprStr)throws IOException {HashMap<String, Integer> map = new HashMap<String, Integer>();// 解析有几个参数要传递for (char ch : exprStr.toCharArray()) {if (ch != '+' && ch != '-') {// 解决重复参数的问题if (!map.containsKey(String.valueOf(ch))) {System.out.print("请输入" + ch + "的值:");String in = (new BufferedReader(new InputStreamReader(System.in))).readLine();map.put(String.valueOf(ch), Integer.valueOf(in));}}}return map;}}abstract class Expression {public abstract int intercepter(Map<String, Integer> args);}class TerminalExpression extends Expression {private String key;public TerminalExpression(String key) {this.key = key;}@Overridepublic int intercepter(Map<String, Integer> args) {return args.get(key);}}abstract class SymbolExpression extends Expression {protected Expression left;protected Expression right;public SymbolExpression(Expression left, Expression right) {this.left = left;this.right = right;}}class AddExpression extends SymbolExpression {public AddExpression(Expression left, Expression right) {super(left, right);}@Overridepublic int intercepter(Map<String, Integer> args) {return left.intercepter(args) + right.intercepter(args);}}class SubExpression extends SymbolExpression {public SubExpression(Expression left, Expression right) {super(left, right);}@Overridepublic int intercepter(Map<String, Integer> args) {return left.intercepter(args) - right.intercepter(args);}}class Calculator {private Expression expression;public Calculator(String expStr) {Stack<Expression> stack = 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 = stack.pop();right = new TerminalExpression(String.valueOf(charArray[++i]));stack.push(new AddExpression(left, right));break;case '-':left = stack.pop();right = new TerminalExpression(String.valueOf(charArray[++i]));stack.push(new SubExpression(left, right));break;default:stack.push(new TerminalExpression(String.valueOf(charArray[i])));}}this.expression = stack.pop();}public int run(Map<String, Integer> args) {return this.expression.intercepter(args);}}