首页 > 代码库 > Interpreter

Interpreter

#include <string>#include <iostream>#include <stack>using namespace std;stack<char> g_stack;class Context{public:    void SetExpression(string sExpr) { m_sExpr = sExpr; }    string GetExpression() const { return m_sExpr; }private:    string m_sExpr;};class Interpreter{public:    virtual void Translate(const Context& context)=0;};class ConcreteInterpreterA : public Interpreter{public:    void Translate(const Context& context);};class ConcreteInterpreterB : public Interpreter{public:    void Translate(const Context& context);};void ConcreteInterpreterA::Translate(const Context& context){    size_t len = context.GetExpression().size();        if (len == 0 || len % 2 != 0)    {        cerr<<"TranslateA failed! mismatch brackets"<<endl;    }    else    {        cout<<"TranslateA go through!"<<endl;    }}void ConcreteInterpreterB::Translate(const Context& context){    while (!g_stack.empty()) g_stack.pop();        string sExpression = context.GetExpression();    for (unsigned int i = 0; i < sExpression.size(); i++)    {        if (sExpression[i] == () g_stack.push(sExpression[i]);        else if (sExpression[i] == ))        {            if (g_stack.size() == 0 || g_stack.top() != ()            {                cerr<<"TranslateB failed! mismatch brackets"<<endl;                return ;            }            else g_stack.pop();        }        else        {            cout<<"TranslateB failed! invalid character in expression"<<endl;            return ;        }    }    if (g_stack.size() != 0)    {        cerr<<"TranslateB failed! mismatch brackets"<<endl;    }    else    {        cout<<"TranslateB go through!"<<endl;    }}int main(int argc, char *argv[]){    Interpreter* pInterpreterA = NULL, *pInterpreterB = NULL;    Context context;        pInterpreterA = new ConcreteInterpreterA;    pInterpreterB = new ConcreteInterpreterB;    context.SetExpression("");    pInterpreterA->Translate(context);    pInterpreterB->Translate(context);    context.SetExpression("(()");    pInterpreterA->Translate(context);    pInterpreterB->Translate(context);    context.SetExpression("(())");    pInterpreterA->Translate(context);    pInterpreterB->Translate(context);    context.SetExpression("(())()");    pInterpreterA->Translate(context);    pInterpreterB->Translate(context);     delete pInterpreterA;    delete pInterpreterB;            return 0;}

 

Interpreter