码迷,mamicode.com
首页 > 编程语言 > 详细

c++ 行为型模式-解释器(Interpreter)

时间:2020-01-26 11:49:14      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:cte   res   上下   int   声明   rac   ret   ext   alt   

1) 意图

给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子

2) 结构

技术图片

 

  其中

  1. AbstractExpression声明一个抽象的解释操作
  2. TerminalExpression(终结符解释器)实现与文法中的终结符相关联的解释操作
  3. NonterminalExpression(非终结符解释器)对文法中的非终结符实现解释操作
  4. Context(上下文)包含解释器之外的一些全局信息
  5. Client调用解释操作

3) 适用性

  1. 当一个语言需要解释执行,并且可将该语言中的句子表示为一个抽象语法树时,特别是该语法简单,而且不需要考虑效率问题

4) 举例

 1 #include <iostream>
 2 #include <list>
 3 class Context 
 4 {  
 5 private:
 6     std::string m_input;
 7     std::string m_output;
 8 public:
 9     void SetInput(std::string str) { m_input = str; }
10     std::string GetInput() { return m_input; }
11     void SetOutput(std::string str) { m_output = str; }
12     std::string GetOutput() { return m_output; }
13 };
14 
15 class AbstractExpression {
16 public:
17     virtual void Interpret(Context* context) = 0;
18     virtual ~AbstractExpression() {}
19 };
20 
21 class TerminalExpression : public AbstractExpression 
22 {  // 终结符表达式
23 public:
24     void Interpret(Context* context) 
25     {
26         std::cout << "TerminalExpression: " << context->GetInput().c_str() << ", "
27             << context->GetOutput().c_str() << std::endl;
28     }
29 };
30 
31 class NonterminalExpression : public AbstractExpression 
32 {   // 非终结符表达式
33 private:
34     AbstractExpression* m_expression;
35 public:
36     NonterminalExpression(AbstractExpression* expression): m_expression(expression){}
37     void Interpret(Context* context) 
38     {
39         std::cout << "NonterminalExpression: " << context->GetInput().c_str() << ", " 
40             << context->GetOutput().c_str() << std::endl;
41         m_expression->Interpret(context);
42     }
43 };
44 
45 int main() {
46     Context* c = new Context();
47     c->SetInput("Hello");
48     c->SetOutput("World");
49 
50     AbstractExpression* exp1 = new TerminalExpression();
51     AbstractExpression* exp2 = new NonterminalExpression(exp1);
52     exp1->Interpret(c); 
53     exp2->Interpret(c); 
54     delete exp1;
55     delete exp2;
56     system("pause");
57 }

 

c++ 行为型模式-解释器(Interpreter)

标签:cte   res   上下   int   声明   rac   ret   ext   alt   

原文地址:https://www.cnblogs.com/ho966/p/12233841.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!