23种设计模式之解释器模式(行为型,10 Interpreter,c++实现)

时间:2022-03-15 17:09:07

23种设计模式之解释器模式(行为型,10 Interpreter,c++实现)

代码实现:

#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;

}