解析者本身是一个很大的设计模式,重点在于设计这个解析者本身,但是由于解析者本身很难设计,故此完善的解析者模式比较少应用,但是这个设计模式本身的思想却不难。
下面简单实用C++实现一下解析者模式,使用不同的解析者,那么就会对于同样的内容解析出不同的结果。
#include <stdio.h>
#include <string>
using namespace std;
class Context
{
public:
string cmd;
void setContext(string s)
{
cmd = s;
}
};
class InterpreterBase
{
protected:
Context *context;
public:
InterpreterBase(Context *c) : context(c) {}
//不在后面写=0会出现无法解析外部命令错误的virtual void interpret();
virtual void interpret() = 0;
};
class InterpreterIncre:public InterpreterBase
{
public:
InterpreterIncre(Context *c) : InterpreterBase(c) {}
void interpret()
{
string cmd = context->cmd;
for (int i = 0; i < (int)cmd.size(); i++)
{
putchar(cmd[i]+1);
}
putchar('\n');
}
};
class InterpreterDecre:public InterpreterBase
{
public:
InterpreterDecre(Context *c) : InterpreterBase(c) {}
void interpret()
{
string cmd = context->cmd;
for (int i = 0; i < (int)cmd.size(); i++)
{
putchar(cmd[i]-1);
}
putchar('\n');
}
};
int main()
{
Context context;
context.setContext("ABCDEFG");
InterpreterDecre decre(&context);
InterpreterIncre incre(&context);
decre.interpret();
incre.interpret();
return 0;
}
运行结果对同一个字符串ABCDEFG,使用不同的解析者得到不同的结果:
可以说C\C++编译器就是利用这个设计模式写出来的。完善实现这样的解析器当然是很难的。