interpreter模式
哦?嗯。。我不懂啊。这有啥用?
反正写法就那样了,先记着吧
interpreter.h
#ifndef _INTERPRETER_H
#define _INTERPRETER_H
#include <iostream>
#include <string>
using namespace std;
class Context
{
public:
Context() {
cout << "context" << endl;
}
~Context() {
}
};
class AbstractExpression
{
public:
virtual ~AbstractExpression() {
}
virtual void Interpret(const Context& c) {
}
protected:
AbstractExpression() {
}
};
class TerminalExpression : public AbstractExpression
{
public:
TerminalExpression(const string& statement) : _statement(statement) {
}
~TerminalExpression() {
}
void Interpret(const Context& c) {
cout << _statement << " TerminalExpression" << endl;
}
private:
string _statement;
};
class NonterminalExpression : public AbstractExpression
{
public:
NonterminalExpression(AbstractExpression* expression, int times) :
_times(times), _expression(expression) {
}
~NonterminalExpression() {
}
void Interpret(const Context& c) {
for (int i = 0; i < _times; i++) {
_expression->Interpret(c);
}
}
private:
int _times;
AbstractExpression* _expression;
};
#endif // _INTERPRETER_H
interpreter.cpp
#include "interpreter.h"
int main()
{
Context* c= new Context();
AbstractExpression* te = new TerminalExpression("hello");
AbstractExpression* nte = new NonterminalExpression(te, 2);
nte->Interpret(*c);
return 0;
}
编译:make interpreter