Interpreter mode (interpreter): Given a language, defines a representation of its grammar and defines an interpreter that uses that representation to interpret sentences in the language.
Interpreter mode resolves a problem: if a particular type of problem occurs at a sufficiently high frequency, it might be worthwhile to describe each instance of the problem as a sentence in a simple language. This allows you to build an interpreter that solves the problem by interpreting these sentences.
The regular expression is one of its applications, the interpreter defines a grammar for regular expressions and represents a specific regular expression, and how to interpret the regular expression.
Four characters:
Abstractexpression abstract expression: declares an abstract interpretation operation that is shared by all nodes in the abstract syntax tree.
Terminalexpression Terminator expression: implements the interpreted operation associated with Terminator in the grammar.
Nonterminalexpression: Non-terminator expression that interprets the non-terminator in grammar. To each rule in grammar R1, R2 ... RN requires a specific non-Terminator expression class.
Context: Contains some global information outside of the interpreter.
Pattern implementation:
[Code]//contextclass context{private: std::string input;public: std::string input (std::string in) { input = in; return input; }};/ /abstract Expression Class Abstractexpression{public: virtual void interpret (Context *context) = 0;};/ /Terminator Expression class Terminalexpression:public Abstractexpression{public: void Interpret (Context *context) override{ std::cout << "terminalexpression\n"; }};/ /Non-Terminator expression class Nonterminalexpression:public Abstractexpression{public: void Interpret (Context *context) override { std::cout << "nonterminalexpression\n"; }};
Client:
[Code]//clientint Main () { context *context = new Context; std::list<abstractexpression*> list; List.push_back (new terminalexpression); List.push_back (new nonterminalexpression); List.push_back (new terminalexpression); List.push_back (new terminalexpression); for (auto i:list) I->interpret (context); Output: //Terminalexpression //nonterminalexpression //terminalexpression // Terminalexpression return 0;}
Interpreter Mode Benefits:
There is usually a language that needs to be interpreted for execution, and the interpreter pattern can be used when a sentence in that language is represented as an abstract syntax tree.
The above is the C + + design mode shallow knowledge of the content of the interpreter mode, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!