行为型模式之解释器模式

#include<iostream>
using namespace std;

class Context
{
public:
	Context(int num)
	{
		m_num = num;
	}

	void setNum(int num)
	{
		m_num = num;
	}

	void setRes(int res)
	{
		m_res = res;
	}

	int getNum()
	{
		return m_num;
	}

	int getRes()
	{
		return m_res;
	}

private:
	int m_num;
	int m_res;
};

class Expression
{
public:
	virtual void interpreter(Context *context) = 0;
};

class Plus :public Expression
{
public:
	virtual void interpreter(Context *context)
	{
		int num = context->getNum();
		num++;
		context->setRes(num);
	}
};

class Minus :public Expression
{
public:
	virtual void interpreter(Context *context)
	{
		int num = context->getNum();
		num--;
		context->setRes(num);
	}
};



void main()
{
	Context *context = NULL;
	Expression *expression = NULL;

	context = new Context(20);

	expression = new Plus;
	expression->interpreter(context);
	cout << context->getRes() << endl;

	delete expression;

	expression = new Minus;
	expression->interpreter(context);
	cout << context->getRes() << endl;
}

阅读更多
上一篇行为型模式之状态模式
下一篇行为型模式之迭代器模式
想对作者说点什么? 我来说一句

解释器模式

2012年09月29日 168KB 下载

没有更多推荐了,返回首页

关闭
关闭