解释器模式(interpretor)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <string> 3 #include <vector> 4 #include <stdio.h> 5 using namespace std; 6 7 //抽象的表达式对象以及Context对象 8 //用于保存计算的中间结果以及当前执行的操作符 9 class Context { 10 public: 11 int m_value; 12 char m_operator; 13 Context() :m_value(0), m_operator('\0') { 14 15 } 16 }; 17 //1+3-2 18 19 //表示所有表达式的抽象接口 20 class IExpression { 21 public: 22 virtual void Eval(Context* p) = 0; 23 }; 24 25 //拆分表达式的元素 26 class Operator :public IExpression { 27 public: 28 Operator(char op) { 29 this->m_op = op; 30 } 31 void Eval(Context *pContext) { 32 pContext->m_operator = m_op; 33 } 34 private: 35 char m_op; 36 }; 37 38 //拆分操作数 39 class Operand :public IExpression { 40 public: 41 Operand(int num) { 42 this->m_num = num; 43 } 44 void Eval(Context* pContext) { 45 switch (pContext->m_operator) 46 { 47 case '\0':pContext->m_value = m_num;break; 48 case '+':pContext->m_value += m_num;break; 49 case '-':pContext->m_value -= m_num;break; 50 default: 51 break; 52 } 53 } 54 private: 55 int m_num; 56 }; 57 58 class Calculator { 59 public: 60 int Calc(string expression) { 61 Context* pCpontext = new Context; 62 vector<IExpression*> tree; 63 for (int i = 0;i < expression.size();i++) { 64 if ((expression[i] == '+') || (expression[i] == '-')) { 65 tree.push_back(new Operator(expression[i])); 66 printf("第%d次压入的符号是=%c\n", i, expression[i]); 67 } 68 else { 69 tree.push_back(new Operand((int)(expression[i] - 48))); 70 printf("第%d次压入的数字是=%d\n", i,((int)( expression[i]-48))); 71 } 72 } 73 for (vector<IExpression*>::iterator iter = tree.begin();iter != tree.end();iter++) { 74 (*iter)->Eval(pCpontext); 75 printf("value=%d,oper=%c\n", pCpontext->m_value, pCpontext->m_operator); 76 } 77 return pCpontext->m_value; 78 } 79 }; 80 81 int main(void) { 82 Calculator* pc = new Calculator; 83 cout << "1+4-2=" << pc->Calc("1+4-2") << endl; 84 system("pause"); 85 return 0; 86 }