标签:
解释器模式:
给定一个语言,定义了它的文法的一种表示,并定义了一个解释器,这个解释器使用该表示来解释语言中的句子。
Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
UML图:
主要包括:
C++实现:
#include <iostream>
#include <list>
using namespace std;
class Context
{
};
class AbstractExpression
{
public:
virtual void interpret(Context * c)=0;
};
class TerminalExpression:public AbstractExpression
{
public:
void interpret(Context *c)
{
cout<<"TerminalExpression interpret"<<endl;
}
};
class NonTerminalExpression:public AbstractExpression
{
public:
void interpret(Context *c)
{
cout<<"NonTerminalExpression interpret"<<endl;
}
};
int main()
{
cout<<"解释器模式代码"<<endl;
list<AbstractExpression *> lists;
Context *c=new Context;
AbstractExpression * te1=new TerminalExpression();
lists.push_back(te1);
AbstractExpression * te2=new TerminalExpression();
lists.push_back(te2);
AbstractExpression * te3=new TerminalExpression();
lists.push_back(te3);
AbstractExpression * te4=new TerminalExpression();
lists.push_back(te4);
AbstractExpression * nte1=new NonTerminalExpression();
lists.push_back(nte1);
list<AbstractExpression*>::iterator iter=lists.begin();
for(;iter!=lists.end();iter++)
{
(*iter)->interpret(c);
}
delete c;
delete te1;
delete te2;
delete te3;
delete te4;
delete nte1;
return 0;
}
执行输出:
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/u012501459/article/details/46697385