解释器模式实例

以下咱们经过对算术表达式的解释来看一个解释器模式的实现, 解释器模式的详细说明见上一个博客http://www.javashuo.com/article/p-elcdnruf-kg.html
如表达式m+n+p中,若是咱们使用解释器模式对该表达式进行解释,那么m,n,p表明的三个字母能够当作是终结符号,而+表明的运算符则能够当作是非终结符号。html

 

首先创建抽象解释器表示数学运算express

public abstract class ArithmeticExpression {

  public abstract int interptet();
}

 

解释器中定义了interptet()方法,ArithmeticExpression有两个直接子类,NumExpression,和OperatorExpression。ide

创建NumExpression,对数字进行解释spa

public class NumExpression extends ArithmeticExpression {
  private int num;

  public NumExpression(int _num) {
    num = _num;
  }

  @Override public int interptet() {
    return num;
  }
}

 

创建OperatorExpression,对运算符进行解释code

public abstract class OperatorExpression extends ArithmeticExpression {
  protected ArithmeticExpression mArithmeticExpression1,mArithmeticExpression2;

  public OperatorExpression(ArithmeticExpression _arithmeticExpression1,
      ArithmeticExpression _arithmeticExpression2) {
    mArithmeticExpression1 = _arithmeticExpression1;
    mArithmeticExpression2 = _arithmeticExpression2;
  }
}

 

AdditionExpression,OperatorExpression的直接子类,加法运算解释器htm

public class AdditionExpression extends OperatorExpression {
  public AdditionExpression(ArithmeticExpression _arithmeticExpression1,
      ArithmeticExpression _arithmeticExpression2) {
    super(_arithmeticExpression1, _arithmeticExpression2);
  }

  @Override public int interptet() {
    return mArithmeticExpression1.interptet() + mArithmeticExpression2.interptet();
  }
}

 

新增业务逻辑处理类,对于数字进行加法操做blog

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();
  }
}

 

客户端调用element

// 解释计算123+124+125+126的运算结果
Calculator calculator = new Calculator("123+124+125+126");
Log.d(TAG, "setBtnClick: -->" + calculator.calculate());

 

这是一个简单的解释器模式,只对数字进行加法运算。同理,咱们还能够写出四则运算等程序。get

相关文章
相关标签/搜索