24行为型模式之解释模式
概念
角色和职责
Context
解释器上下文环境类。用来存储解释器的上下文环境,比如需要解释的文法等。
AbstractExpression
解释器抽象类。
ConcreteExpression
解释器具体实现类。
适用于:
解释器根据中介结果实现对应的运算。
案例
//加号、减号解释器,根据上下文储存内容再加载到解释器中,进行对应的运算
#include <iostream> using namespace std; #include "string"
//保存中间结果 class Context { public: Context(int num) { m_num = num; } public: void setNum(int num) { m_num = num; } int getNum() { return m_num; } void setRes(int res) { m_res = res; } int getRes() { return m_res; } private: int m_num; int m_res; }; //加号解释器 class Expression { public: virtual void interpreter(Context *context) = 0; }; class PlusExpression : public Expression { public: virtual void interpreter(Context *context) { int num = context->getNum(); num ++ ; context->setNum(num); context->setRes(num); } }; //减法解释器 class MinusExpression : public Expression { public: virtual void interpreter(Context *context) { int num = context->getNum(); num -- ; context->setNum(num); context->setRes(num); } }; void main() { Context *pcxt = new Context(10); Expression *e1 = new PlusExpression; e1->interpreter(pcxt); cout << "PlusExpression:" << pcxt->getRes() << endl; Expression *e2 = new MinusExpression; e2->interpreter(pcxt); cout << "MinusExpression:" << pcxt->getRes() << endl; delete e2; delete e1; system("pause"); return ; }