解釋器模式實例

以下咱們經過對算術表達式的解釋來看一個解釋器模式的實現, 解釋器模式的詳細說明見上一個博客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

相關文章
相關標籤/搜索