Interpreter Pattern

1.Interpreter模式的目的就是提供一个一门定义语言的语法表示的解释器,然后通过这个解释器来解释语言中的句子。

2.Interpreter模式结构图

3.实现

 1 #ifndef _CONTEXT_H_ 
 2 #define _CONTEXT_H_
 3 
 4 class Context 
 5 { 
 6 public:
 7     Context();
 8     ~Context();
 9 protected:
10 private:
11 };
12 
13 #endif
Context.h
 1 #include "Context.h"
 2 
 3 Context::Context() 
 4 {
 5 
 6 }
 7 Context::~Context() 
 8 {
 9 
10 }
Context.cpp
 1 #ifndef _INTERPRET_H_
 2 #define _INTERPRET_H_
 3 
 4 #include "Context.h" 
 5 #include <string> 
 6 using namespace std;
 7 
 8 class AbstractExpression 
 9 { 
10 public: 
11     virtual ~AbstractExpression();
12     virtual void Interpret(const Context& c);
13 
14 protected: 
15     AbstractExpression();
16 private:
17 };
18 
19 class TerminalExpression:public AbstractExpression 
20 {
21 public: 
22     TerminalExpression(const string& statement);
23     ~ TerminalExpression();
24     void Interpret(const Context& c);
25 
26 protected:
27 private: 
28     string _statement; 
29 };
30 
31 class NonterminalExpression:public AbstractExpression 
32 { 
33 public:
34     NonterminalExpression(AbstractExpression* expression,int times);
35     ~ NonterminalExpression();
36     void Interpret(const Context& c);
37 protected:
38 private: 
39     AbstractExpression* _expression;
40     int _times; 
41 };
42 
43 #endif
Interpret.h
 1 #include "Interpret.h" 
 2 #include <iostream> 
 3 using namespace std;
 4 
 5 AbstractExpression::AbstractExpression() 
 6 {
 7 
 8 }
 9 AbstractExpression::~AbstractExpression()
10 {
11 
12 }
13 void AbstractExpression::Interpret(const Context& c) 
14 {
15 
16 }
17 TerminalExpression::TerminalExpression(const string& statement)
18 { 
19     this->_statement = statement; 
20 }
21 TerminalExpression::~TerminalExpression()
22 {
23 
24 }
25 void TerminalExpression::Interpret(const Context& c) 
26 { 
27     cout<<this->_statement<<" TerminalExpression"<<endl;
28 }
29 NonterminalExpression::NonterminalExpression(AbstractExpression* expression,int times)
30 { 
31     this->_expression = expression;
32     this->_times = times; 
33 }
34 NonterminalExpression::~NonterminalExpression() 
35 {
36 
37 }
38 void NonterminalExpression::Interpret(const Context& c) 
39 { 
40     for (int i = 0; i < _times ; i++) 
41     { 
42         this->_expression->Interpret(c); 
43     } 
44 }
Interpret.cpp
 1 #include "Context.h" 
 2 #include "Interpret.h" 
 3 #include <iostream> 
 4 using namespace std;
 5 
 6 int main(int argc,char* argv[])
 7 {
 8     Context* c = new Context();
 9     AbstractExpression* te = new TerminalExpression("hello");
10     AbstractExpression* nte = new NonterminalExpression(te,2);
11     nte->Interpret(*c);
12 
13     return 0; 
14 }
main.cpp

 

posted on 2015-07-24 15:55  那个人好像一条狗  阅读(296)  评论(0编辑  收藏  举报