首页 > 代码库 > 解释器模式

解释器模式

解释器(interpreter)模式

意图:给定一个语言,定义它的文法表示,并定义一个解释器,这个解释器使用该标识来解释语言中的句子。

主要解决:对于一些固定文法构建一个解释句子的解释器。

 

代码:

#include <iostream>
#include <map>
#include <string>
using namespace std;

#define SAFE_DELETE(p) if ((p)) {delete (p); (p) = NULL;}

class Context
{
public:
    void addValue(string key, int value)
    {
        //_valueMap.insert(pair<string, int>(key, value));
        _valueMap[key] = value;
    
    }

    int getValue(string key) const
    {
        return _valueMap.at(key);
    }

private:
    map<string, int> _valueMap;
};

class AbstractExpression
{
public:
    virtual ~AbstractExpression() {}
    virtual int interpreter(const Context &context) = 0;
};

class AddNonterminalExpression : public AbstractExpression
{
public:
    AddNonterminalExpression(AbstractExpression *left, AbstractExpression *right) : _left(left), _right(right){}
    ~AddNonterminalExpression()
    {
        SAFE_DELETE(_left);
        SAFE_DELETE(_right);
    }
virtual int interpreter(const Context &context) { return _left->interpreter(context) + _right->interpreter(context); } private: AbstractExpression *_left; AbstractExpression *_right; }; class SubstractNonterminalExpression : public AbstractExpression { public: SubstractNonterminalExpression(AbstractExpression *left, AbstractExpression *right) : _left(left), _right(right){} ~SubstractNonterminalExpression() { SAFE_DELETE(_left); SAFE_DELETE(_right); }
virtual int interpreter(const Context &context) { return _left->interpreter(context) - _right->interpreter(context); } private: AbstractExpression *_left; AbstractExpression *_right; }; class TerminalExpression : public AbstractExpression { public: TerminalExpression(string key) { _key = key; }
int interpreter(const Context &context) { return context.getValue(_key); } private: string _key; }; void test() { Context cxt; cxt.addValue("a", 1); cxt.addValue("b", 3); cxt.addValue("c", 5); // 1 + 3 AbstractExpression *addExpr = new AddNonterminalExpression(new TerminalExpression("a"), new TerminalExpression("b")); cout << addExpr->interpreter(cxt) << endl; // 4 - 5 AbstractExpression *subExpr = new SubstractNonterminalExpression(addExpr, new TerminalExpression("c")); cout << subExpr->interpreter(cxt) << endl; delete subExpr; } int main() { test(); cin.get(); return 0; }

 

解释器模式