码迷,mamicode.com
首页 > 其他好文 > 详细

Interpreter

时间:2014-12-23 10:17:24      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

#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

标签:

原文地址:http://www.cnblogs.com/stanley198610281217/p/4179507.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!