定義:解釋器模式(interpreter),給定一個語言,定義它的文法的一種表示,並定義一個解釋器,這個解釋器使用該表示來解釋語言中的句子。
UML:
// Interpreter.cpp : 定義控制檯應用程序的入口點。
//
#include "stdafx.h"
#include <iostream>
#include <list>
using namespace std;
struct Context
{
string input;
string output;
};
class AbstractExpression
{
public:
virtual void Interpret(Context *context) = 0;
};
class TerminalExpression : public AbstractExpression
{
public:
void Interpret(Context *context)
{
cout << "終端解釋器" << endl;
}
};
class NonterminalExpression : public AbstractExpression
{
public:
void Interpret(Context *context)
{
cout << "非終端解釋器" << endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Context *context = new Context();
list<AbstractExpression *> list;
list.push_back(new TerminalExpression());
list.push_back(new NonterminalExpression());
list.push_back(new TerminalExpression());
list.push_back(new TerminalExpression());
auto it = list.begin();
for (; it != list.end(); ++it)
{
(*it)->Interpret(context);
}
return 0;
}
輸出: