介绍
参与者
实现代码
#include <iostream>
#include <map>
class Context;
class Expression {
public:
virtual int interpreter(Context *) = 0;//一定会有解释方法
virtual ~Expression() = default;
};
class Context{
public:
int getVal(Expression *expression)
{
auto it = m.find(expression);
if(m.end() != it)
{
return it->second;
}
return 0;
}
void insert(Expression *expression,int val)
{
m.insert(std::make_pair(expression,val));
}
private:
std::map<Expression*,int> m;
};
class TerminalExpression :public Expression{
public:
explicit TerminalExpression(std::string name_)
{
name = name_;
}
int interpreter(Context *context) override
{
return context->getVal(this);
}
~TerminalExpression() override = default;
private:
std::string name;
};
class NonTerminalExpressinon : public Expression{
public:
NonTerminalExpressinon(Expression *ee1,Expression *ee2)
{
e1 = ee1;
e2 = ee2;
}
Expression *e1;
Expression *e2;
int interpreter(Context *context) override
{
return 0;
}
~NonTerminalExpressinon() override = default;
};
class Plus : public NonTerminalExpressinon {
public:
Plus(Expression *ee1,Expression *ee2):NonTerminalExpressinon(ee1,ee2)
{
}
int interpreter(Context *context) override
{
return e1->interpreter(context) + e2->interpreter(context);
}
~Plus() override = default;
};
class Minus : public NonTerminalExpressinon {
public:
Minus(Expression *ee1,Expression *ee2):NonTerminalExpressinon(ee1,ee2)
{
}
int interpreter(Context *context) override
{
return e1->interpreter(context) - e2->interpreter(context);
}
~Minus() override = default;
};
int main()
{
auto *context = new Context();
Expression *e1 = new TerminalExpression("a");
Expression *e2 = new TerminalExpression("b");
Expression *e3 = new TerminalExpression("c");
context->insert(e1,44);
context->insert(e2,55);
context->insert(e3,77);
Expression* plus = new Plus(new Minus(e1,e2),e3);
auto ret = plus->interpreter(context);
std::cout<<"输出结果为:"<<ret<<std::endl;
}
输出结果
输出结果为:66
特点
参考