InterpreterPattern.cpp 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. class Context { };
  5. class Expression {
  6. public:
  7. virtual ~Expression() { }
  8. virtual void Interpret(const Context& c) = 0;
  9. };
  10. class TerminalExpression :public Expression {
  11. public:
  12. TerminalExpression(const string& statement) {
  13. _statement = statement;
  14. }
  15. void Interpret(const Context& c) {
  16. cout << this->_statement << " -- TerminalExpression" << endl;
  17. }
  18. private:
  19. string _statement;
  20. };
  21. class NonterminalExpression :public Expression {
  22. public:
  23. NonterminalExpression(Expression* expression, int times) {
  24. _expression = expression;
  25. _times = times;
  26. }
  27. void Interpret(const Context& c) {
  28. for (int i = 0; i < _times; i++) {
  29. _expression->Interpret(c);
  30. }
  31. }
  32. private:
  33. Expression *_expression;
  34. int _times;
  35. };
  36. int main() {
  37. Context *c = new Context();
  38. Expression *tp = new TerminalExpression("echo");
  39. Expression *ntp = new NonterminalExpression(tp, 4);
  40. ntp->Interpret(*c);
  41. delete ntp;
  42. delete tp;
  43. delete c;
  44. return 0;
  45. }