/**解释模式 * 用解释器模式来实现 加减乘除四则运算 * Created by nicknailo on 2018/8/30. */ public class InterpretPattern { public static void main(String[] args) { Calculator calculator = new Calculator("123 + 124 + 125 - 126"); System.out.println(calculator.calculate()); } } abstract class ArithmeticExpression { public abstract int interptet(); } class NumExpression extends ArithmeticExpression { private int num; public NumExpression(int _num) { num = _num; } @Override public int interptet() { return num; } } abstract class OperatorExpression extends ArithmeticExpression { protected ArithmeticExpression mArithmeticExpression1,mArithmeticExpression2; public OperatorExpression(ArithmeticExpression _arithmeticExpression1, ArithmeticExpression _arithmeticExpression2) { mArithmeticExpression1 = _arithmeticExpression1; mArithmeticExpression2 = _arithmeticExpression2; } } class AdditionExpression extends OperatorExpression { public AdditionExpression(ArithmeticExpression _arithmeticExpression1, ArithmeticExpression _arithmeticExpression2) { super(_arithmeticExpression1, _arithmeticExpression2); } @Override public int interptet() { return mArithmeticExpression1.interptet() + mArithmeticExpression2.interptet(); } } class PlusExpression extends OperatorExpression { public PlusExpression(ArithmeticExpression _arithmeticExpression1, ArithmeticExpression _arithmeticExpression2) { super(_arithmeticExpression1, _arithmeticExpression2); } @Override public int interptet() { return mArithmeticExpression1.interptet() - mArithmeticExpression2.interptet(); } } class Calculator { protected Stack<ArithmeticExpression> mArithmeticExpressionStack = new Stack<ArithmeticExpression>(); public Calculator(String expression) { ArithmeticExpression arithmeticExpression1, arithmeticExpression2; String[] elements = expression.split(" "); for (int i = 0; i < elements.length; ++i) { System.out.println("elements: " + Arrays.toString(elements)); System.out.println("elements[i]: " + elements[i].charAt(0)); switch (elements[i].charAt(0)) { case '+': arithmeticExpression1 = mArithmeticExpressionStack.pop(); System.out.println("stack.pop : = "+ arithmeticExpression1.interptet()); arithmeticExpression2 = new NumExpression(Integer.valueOf(elements[++i])); mArithmeticExpressionStack.push( new AdditionExpression(arithmeticExpression1, arithmeticExpression2)); break; case '-': arithmeticExpression1 = mArithmeticExpressionStack.pop(); System.out.println("stack.pop : = "+ arithmeticExpression1.interptet()); arithmeticExpression2 = new NumExpression(Integer.valueOf(elements[++i])); mArithmeticExpressionStack.push( new PlusExpression(arithmeticExpression1, arithmeticExpression2)); break; default: mArithmeticExpressionStack.push(new NumExpression(Integer.valueOf(elements[i]))); break; } } } public int calculate() { return mArithmeticExpressionStack.pop().interptet(); } }