設計模式-----------------(Interpreter模式)直譯器模式
阿新 • • 發佈:2019-02-14
直譯器的目的就是使用一個直譯器為使用者提供一個一門語言的語法表示的直譯器,然後通過這個直譯器來解釋語言中的句子。
下面就來寫下這個結構圖的具體實現。
class Context;
class AbstractExpression;
class TerminalExpression:public AbstractExpression;
class NonterminalExpression: public AbstractExpression;
#pragma once
#include <string>
using namespace std;
class Context
{
public :
Context(string str);
~Context();
string GetValue()const
{
return _mValue;
}
protected:
private:
string _mValue;
};
#include "stdafx.h"
#include "Context.h"
Context::Context(string str)
{
_mValue = str;
}
Context::~Context()
{
}
#ifndef _INTERPRET_H
#define _INTERPRET_H
#include "stdafx.h"
#include "Context.h"
#include <string>
using namespace std;
class AbstructExpression{
public:
virtual ~AbstructExpression();
virtual void Interpret(const Context& c);
protected:
AbstructExpression();
private:
};
class TerminalExpression :public AbstructExpression{
public:
TerminalExpression(const string& statement);
~TerminalExpression();
void Interpret(const Context& c);
protected:
private:
string _statement;
};
class NonterminalExpression :public AbstructExpression{
public:
NonterminalExpression(AbstructExpression* expresiion, int times);
~NonterminalExpression();
void Interpret(const Context& c);
protected:
private:
AbstructExpression* _expression;
int _times;
};
#endif
#include "stdafx.h"
#include "interpret.h"
#include <iostream>
using namespace std;
AbstructExpression::AbstructExpression(){
}
AbstructExpression::~AbstructExpression(){
}
void AbstructExpression::Interpret(const Context& c){
}
TerminalExpression::TerminalExpression(const string& statement){
this->_statement = statement;
}
TerminalExpression::~TerminalExpression(){
}
void TerminalExpression::Interpret(const Context& c){
cout << this->_statement << " TermimalExpression " << c.GetValue() <<endl;
}
NonterminalExpression::NonterminalExpression(AbstructExpression* expresiion, int times){
this->_expression = expresiion;
this->_times = times;
}
NonterminalExpression::~NonterminalExpression(){
}
void NonterminalExpression::Interpret(const Context& c){
for (int i = 0; i < _times; i++){
this->_expression->Interpret(c);
}
}
// interpretr.cpp : 定義控制檯應用程式的入口點。
//
#include "stdafx.h"
#include "interpret.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
Context*c = new Context("123");
AbstructExpression * te = new TerminalExpression("hello");
te->Interpret(*c);
AbstructExpression* nte = new NonterminalExpression(te, 2);
nte->Interpret(*c);
getchar();
getchar();
return 0;
}