标签:
PRINT MyLanguage: NEXTLINE
LOOP 2
PRINT Hello SPACE
PRINT world!
NEXTLINE- BREAK
- END
class Context {
public:
Context(const string str)
{
m_size = splitStr(str, m_strs);
}
string current()
{
return m_strs[m_size];
}
string next()
{
return m_strs[++m_size];
}
private:
vector<string> m_strs;
int m_size;
}
class AbstractExpression {
public:
virtual void interpret(Context* context) = 0;
virtual void execute() = 0;
}
class IteratorExpression : public AbstractExpression {
public:
virtual void interpret(Context* context);
virtual void execute();
private:
vector<AbstractExpression*> m_exps;
}
void IteratorExpression::interpret(Context* context)
{
while(context->current() != "END")
{
if(context->current() == "LOOP")
{
LoopExpression* loopExp = new LoopExpression(context);
m_exp.insert(loopExp);
}
else
{
CommandExpresion* cmdExp = new CommandExpression(context);
m_exps.insert(cmdExp);
}
}
}
void IteratorExpresion::execute()
{
for(int i = 0; i < m_str.size(); ++i)
m_exps[i]->execute();
}
class LoopExpression : public AbstractExpresion
{
public:
virtual void interpret(Context* context);
virtual void execute();
private:
vector<AbstractExpression*> m_exps;
int m_count;
}
void LoopExpression::interpret(Context* context)
{
while(context->current() != "BREAK")
{
if(context->current() == "LOOP")
{
m_count = context->next().toInt();
}
else
{
CommandExpresion* cmdExp = new CommandExpression(context);
m_exps.insert(cmdExp);
}
}
}
void LoopExpression::execute()
{
for(int i = 0; i < m_count; ++i)
for(int j = 0; j < m_exps.size(); ++j)
m_exps[j]->execute();
}
class CommandExpression : public AbstractExpression
{
public:
virtual void interpret(Context* context);
virtual void execute();
private:
string m_name;
string m_text;
}
void CommandExpression::interpret(Context* context)
{
m_name = context->current();
if(context->current() == "PRINT")
{
m_text = context->next();
}
context->next();
}
void CommandExpression::execute()
{
if(m_name == "PRINT")
cout << m_text;
else if(m_name == "NEXTLINE")
cout << endl;
else if(m_name == "SPACE")
cout << " ";
}
string str = "PRINT MyLanguage: NEXTLINE LOOP 2 PRINT Hello SPACE PRINT world! NEXTLINE BREAK END";
Context* context = new Context(str);
IteratorExpression* iterExp = new IteratorExpression();
iterExp->interpret(context);
iterExp->execute();
MyLauguage:
Hello world!
Hello world!
标签:
原文地址:http://www.cnblogs.com/mengfanrong/p/4329814.html