interpreter模式

作者: 老练子丶2017 | 来源:发表于2017-11-23 22:03 被阅读0次

    哦?嗯。。我不懂啊。这有啥用?

    反正写法就那样了,先记着吧

    interpreter.h

    #ifndef _INTERPRETER_H

    #define _INTERPRETER_H

    #include <iostream>

    #include <string>

    using namespace std;

    class Context

    {

    public:

    Context() {

    cout << "context" << endl;

    }

    ~Context() {

    }

    };

    class AbstractExpression

    {

    public:

    virtual ~AbstractExpression() {

    }

    virtual void Interpret(const Context& c) {

    }

    protected:

    AbstractExpression() {

    }

    };

    class TerminalExpression : public AbstractExpression

    {

    public:

    TerminalExpression(const string& statement) : _statement(statement) {

    }

    ~TerminalExpression() {

    }

    void Interpret(const Context& c) {

    cout << _statement << " TerminalExpression" << endl;

    }

    private:

    string _statement;

    };

    class NonterminalExpression : public AbstractExpression

    {

    public:

    NonterminalExpression(AbstractExpression* expression, int times) :

    _times(times), _expression(expression) {

    }

    ~NonterminalExpression() {

    }

    void Interpret(const Context& c) {

    for (int i = 0; i < _times; i++) {

    _expression->Interpret(c);

    }

    }

    private:

    int _times;

    AbstractExpression* _expression;

    };

    #endif // _INTERPRETER_H

    interpreter.cpp

    #include "interpreter.h"

    int main()

    {

    Context* c= new Context();

    AbstractExpression* te = new TerminalExpression("hello");

    AbstractExpression* nte = new NonterminalExpression(te, 2);

    nte->Interpret(*c);

    return 0;

    }

    编译:make interpreter

    相关文章

      网友评论

        本文标题:interpreter模式

        本文链接:https://www.haomeiwen.com/subject/zumtbxtx.html