行为型模型 解释模型
/** * 行为型模型 解释模型 * 给定一个语言,定义它的文法表示,并定义一个解释器,这个解释器使用该标识来解释语言中的句子。 * */ #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> class Context { public: Context(int num) { m_num = num; } 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 * contex) = 0; virtual ~Expression() {} }; class PlusExpression: public Expression { virtual void interpreter(Context * contex) override { int num = contex->getNum(); num++; contex->setNum(num); contex->setRes(num); } }; class MinusExpression: public Expression { public: virtual void interpreter(Context * contex) override { int num = contex->getNum(); num--; contex->setNum(num); contex->setRes(num); } }; void mytest() { Context *pcxt = new Context(10); Expression *e1 = new PlusExpression(); e1->interpreter(pcxt); std::cout << "PlusExpression: " << pcxt->getRes() << std::endl; Expression *e2 = new MinusExpression(); e2->interpreter(pcxt); std::cout << "MinusExpression: " << pcxt->getRes() << std::endl; delete e2; e2 = nullptr; delete e1; e1 = nullptr; delete pcxt; pcxt = nullptr; return; } int main() { mytest(); system("pause"); return 0; }
时间: 2024-09-29 08:49:41