代码实现:
#include <iostream>
#include <string>
using namespace std;
class Context {
public:
Context()
{
this->setNum(0);
}
void setNum(int num)
{
this->num = num;
}
int getNum()
{
return this->num;
}
private:
int num;
};
class Expression
{
public:
virtual void interpret(Context* context) = 0;
};
class PlusExpression : public Expression
{
public:
virtual void interpret(Context* context)
{
context->setNum(context->getNum() + 1);
}
};
class MinusExpression : public Expression
{
public:
virtual void interpret(Context* context)
{
context->setNum(context->getNum() - 1);
}
};
void main()
{
Context* context = new Context;
cout << context->getNum() << endl;
Expression* plusExp = new PlusExpression;
plusExp->interpret(context);
cout << context->getNum() << endl;
Expression* minusExp = new MinusExpression;
minusExp->interpret(context);
cout << context->getNum() << endl;
delete context;
delete plusExp;
delete minusExp;
}