1. 程式人生 > >設計模式之直譯器模式,C++實現

設計模式之直譯器模式,C++實現

借用下設計模式的圖


程式碼

表示不是比較正規的實現。不過設計模式嘛,隨心而設計,差不多是那個意思,“認真你就輸了

// Interpert.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string>
using namespace std;

// 直譯器模式:給定一種語言,定義它的文法的一種表示,並定義一個直譯器
// 該直譯器使用該表示來解釋語言中的句子

// 類似於程式語言或者指令碼

// 假設情景是一個指令碼控制系統
// wasd上下左右方向,正數數字為移動步數
// 簡化一下吧,測試和開發支援wasd字母,移動步數為1-9的正整數


class Fire
{
public:
	

};

class Action
{
public:
	virtual void Interpret(string &strCmd)
	{
		if (strCmd.length() == 0)
		{
			return;
		}
		else
		{
			string strNum		= strCmd.substr(1, 2);
			m_nNum = atoi(strNum.c_str());
			strCmd = strCmd.substr(2);
			Excute();
		}
	}
	virtual void Excute() = 0;
protected:
	int		m_nNum;

};


// W
class Forward : public Action
{
public:
	void Excute()
	{
		for (int i = 0; i < m_nNum; i ++)
		{
			printf("前進  ");
		}
	}
};

// A
class Left : public Action
{
public:
	void Excute()
	{
		for (int i = 0; i < m_nNum; i ++)
		{
			printf("左移  ");
		}
	}
};

class Right : public Action
{
public:
	void Excute()
	{
		for (int i = 0; i < m_nNum; i ++)
		{
			printf("右移  ");
		}
	}
};

// S
class Back : public Action
{
public:
	void Excute()
	{
		for (int i = 0; i < m_nNum; i ++)
		{
			printf("後退  ");
		}
	}
};

void Interper(string &str)
{
	string tmpStr = str.substr(0,1);
	Action	*pAction = NULL;

	char t;
	memcpy(&t, tmpStr.c_str(), 1);
	switch (t)
	{
	case 'W':
		pAction = new Forward();
		break;
	case 'A':
		pAction = new Left();
		break;
	case 'D':
		pAction = new Right();
		break;
	case 'S':
		pAction = new Back();
		break;
	default:
		break;
	}
	if (pAction)
	{
		pAction->Interpret(str);
		delete pAction;
		pAction = NULL;
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	string str = "A7S4D4W1A5D5";
	while(str.length() != 0)
	{
		Interper(str);
	}
	printf("\n");

	return 0;
}

輸出結果:

左移  左移  左移  左移  左移  左移  左移  後退  後退  後退  後退  右移  右移  右
移  右移  前進  左移  左移  左移  左移  左移  右移  右移  右移  右移  右移
請按任意鍵繼續. . .