Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1862127
  • 博文数量: 496
  • 博客积分: 12043
  • 博客等级: 上将
  • 技术积分: 4778
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-27 14:26
文章分类

全部博文(496)

文章存档

2014年(8)

2013年(4)

2012年(181)

2011年(303)

2010年(3)

分类: C/C++

2012-06-14 10:09:30

目标:通常当一个语言需要解释执行,并且你可以将该语言中的句子表示成为一个抽象的语法树时,可以使用解释器模式。

示例代码:
#include
#include
#include

using namespace std;

class Context;

class AbstractExpression
{
public:
    virtual void Interpret(Context* context)=0;
};

class Expression : public AbstractExpression
{
public:
    virtual void Interpret(Context* context)
    {
        cout << "终端解释器" << endl;
    }
};

class NonterminalExpression : public AbstractExpression
{
public:
    virtual void Interpret(Context* context)
    {
        cout << "非终端解释器" << endl;
    }
};

class Context
{
public:
    string input;
    string output;
};

//客户端
int main()
{
    Context* context = new Context();
    vector express;
    express.push_back(new Expression());
    express.push_back(new NonterminalExpression());
    express.push_back(new NonterminalExpression());
   
    vector::iterator p = express.begin();
    while(p != express.end())
    {
        (*p)->Interpret(context);
        p++;
    }
   
    return 0;
}

阅读(946) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~