设计模式-Interpreter(行为模式) 使用解释器给用户提供一个一门定义语言的语法表示的解释器,通过该解释器解释语言中的句子。
//以下代码来源: 设计模式精解-GoF 23种设计模式解析附C++实现源码
//Context.h
#pragma once class Context { public: Context(); ~Context(); protected: private: };
//Context.cpp
#include"Context.h" Context::Context(){} Context::~Context(){}
//Interpret.h
#include"Context.h" #include<string> class AbstractExpression{ public: virtual ~AbstractExpression(); virtual void Interpret(const Context& c); protected: AbstractExpression(); private: }; class TerminalExpression :public AbstractExpression { public: TerminalExpression(const std::string& statement); ~TerminalExpression(); void Interpret(const Context&c); protected: private: std::string _statement; }; class NonterminalExpression :public AbstractExpression { public: NonterminalExpression(AbstractExpression* expression, int times); ~NonterminalExpression(); void Interpret(const Context& c); protected: private: AbstractExpression* _expression; int _times; };
//Interpret.cpp
#include"Interpret.h" #include"Context.h" #include<iostream> AbstractExpression::AbstractExpression(){} AbstractExpression::~AbstractExpression(){} void AbstractExpression::Interpret(const Context&c) { } TerminalExpression::TerminalExpression(const std::string &statement) { this->_statement = statement; } TerminalExpression::~TerminalExpression(){} void TerminalExpression::Interpret(const Context& c) { std::cout << this->_statement << "TerminalExpression" << std::endl; } NonterminalExpression::NonterminalExpression(AbstractExpression* expression, int times) { this->_expression = expression; this->_times = times; } NonterminalExpression::~NonterminalExpression(){} void NonterminalExpression::Interpret(const Context& c) { for (int i = 0; i < _times; ++i) { this->_expression->Interpret(c); } }
//main.cpp
#include"Context.h" #include"Interpret.h" #include<iostream> #include<string> int main(int args, char* argv) { Context* c = new Context(); AbstractExpression* te = new TerminalExpression("Hello"); AbstractExpression* nte = new NonterminalExpression(te, 2); nte->Interpret(*c); getchar(); return 0; }