目标:通常当一个语言需要解释执行,并且你可以将该语言中的句子表示成为一个抽象的语法树时,可以使用解释器模式。
示例代码:
#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;
}
阅读(959) | 评论(0) | 转发(0) |