如下我们通过对算术表达式的解释来看一个解释器模式的实现, 解释器模式的详细说明见上一个博客https://www.cnblogs.com/fylove/p/9070338.html
如表达式m+n+p
中,如果我们使用解释器模式对该表达式进行解释,那么m,n,p
代表的三个字母可以看成是终结符号,而+
代表的运算符则可以看成是非终结符号。
首先建立抽象解释器表示数学运算
public abstract class ArithmeticExpression { public abstract int interptet(); }
解释器中定义了interptet()方法,ArithmeticExpression有两个直接子类,NumExpression,和OperatorExpression。
建立NumExpression,对数字进行解释
public class NumExpression extends ArithmeticExpression { private int num; public NumExpression(int _num) { num = _num; } @Override public int interptet() { return num; } }
建立OperatorExpression,对运算符进行解释
public abstract class OperatorExpression extends ArithmeticExpression { protected ArithmeticExpression mArithmeticExpression1,mArithmeticExpression2; public OperatorExpression(ArithmeticExpression _arithmeticExpression1, ArithmeticExpression _arithmeticExpression2) { mArithmeticExpression1 = _arithmeticExpression1; mArithmeticExpression2 = _arithmeticExpression2; } }
AdditionExpression,OperatorExpression的直接子类,加法运算解释器
public class AdditionExpression extends OperatorExpression { public AdditionExpression(ArithmeticExpression _arithmeticExpression1, ArithmeticExpression _arithmeticExpression2) { super(_arithmeticExpression1, _arithmeticExpression2); } @Override public int interptet() { return mArithmeticExpression1.interptet() + mArithmeticExpression2.interptet(); } }
新增业务逻辑处理类,对于数字进行加法操作
public class Calculator { protected Stack<ArithmeticExpression> mArithmeticExpressionStack = new Stack<>(); public Calculator(String expression) { ArithmeticExpression arithmeticExpression1, arithmeticExpression2; String[] elements = expression.split(" "); for (int i = 0; i < elements.length; ++i) { switch (elements[i].charAt(0)) { case '+': arithmeticExpression1 = mArithmeticExpressionStack.pop(); arithmeticExpression2 = new NumExpression(Integer.valueOf(elements[++i])); mArithmeticExpressionStack.push( new AdditionExpression(arithmeticExpression1, arithmeticExpression2)); break; default: mArithmeticExpressionStack.push(new NumExpression(Integer.valueOf(elements[i]))); break; } } } public int calculate() { return mArithmeticExpressionStack.pop().interptet(); } }
客户端调用
// 解释计算123+124+125+126的运算结果 Calculator calculator = new Calculator("123+124+125+126"); Log.d(TAG, "setBtnClick: -->" + calculator.calculate());
这是一个简单的解释器模式,只对数字进行加法运算。同理,我们还可以写出四则运算等程序。