24.解释器模式

  给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。
  案例:简谱到音乐的转译(音乐简谱中描绘乐曲用的是1234567,而实际发出的声音却是"哆瑞咪发嗦啦西")。
 

#include <iostream>
#include <string>
#include <vector>
#include <sstream>

using namespace std;

// 待解释文本
class PlayContext
{
public:
	string get_text()
	{
		return this->m_text;
	}

	void set_text(string text)
	{
		this->m_text = text;
	}

private:
	string m_text;
};

// 文法表达式接口
class Expression
{
public:
	virtual void excute(PlayContext* context) = 0;
};

// 音符类,进行具体的音符转换
class Note : public Expression
{
public:
	void excute(PlayContext* context)
	{
		string s = context->get_text();
		string buf;

		if (context->get_text().length() == 0)
		{
			return;
		}
		else
		{
			vector<string> vec;
			stringstream ss(context->get_text());
			while (ss >> buf)
				vec.push_back(buf);

			vector<string>::iterator it;
			for (it = vec.begin(); it != vec.end(); it++)
			{
				int c = stoi(*it);
				switch (c)
				{
				case 1:
					cout << "do" << endl;
					break;
				case 2:
					cout << "re" << endl;
					break;
				case 3:
					cout << "mi" << endl;
					break;
				case 4:
					cout << "fa" << endl;
					break;
				case 5:
					cout << "so" << endl;
					break;
				case 6:
					cout << "la" << endl;
					break;
				case 7:
					cout << "xi" << endl;
					break;
				}
			}
		}
	}
};

void test_01()
{
	PlayContext* context = new PlayContext;
	Expression* note = new Note;
	context->set_text("3 5 6 3 5");
	note->excute(context);

	context->set_text("6 5 3 1 2");
	note->excute(context);

	delete context;
	delete note;
}

int main()
{
	test_01();

	system("pause");
	return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值