当前位置:网站首页>16 interpreter mode
16 interpreter mode
2022-06-22 08:29:00 【Grow some hair.】
Reprint of the original :https://blog.csdn.net/sinat_21107433/article/details/102864850
seen 《 Ming Dynasty 1566》 Do you ? This is a Jungle The most favorite and respected historical drama I have ever seen . All the friends who have seen this play know , Emperor Jiajing never spoke out clearly , But like to talk around , Or a code word , If you don't speculate carefully , I don't know what the real meaning of Jiajing's words is . For example, he told Chen Hong “ Go to the water limit , Sit and watch the clouds rise ”, Chen Hong thought that he would come to the emperor to weed ; The crown prince has a son , Jiajing gave jujubes and chestnuts …… If Jungle Living at that time , The skull is really getting bigger , It's enough to speculate about the emperor's intentions all day . If only there were an interpreter , Be able to interpret the emperor's words as plain language !

1. An overview of interpreter patterns
The Interpreter pattern is used to describe a simple language interpreter , It is mainly applied to the design of the interpreter developed with object-oriented language . When it comes to developing a new language , You can use interpreter mode .
Interpreter mode :
Given a language , A representation of the grammar that defines it , And define an interpreter , This interpreter uses this representation to interpret sentences in a language .
What the Interpreter pattern needs to solve is , If a particular type of problem occurs frequently enough , Then it may be worth expressing each instance of the problem as a sentence in a simple language . In this way, you can construct an interpreter , The interpreter interprets these sentences , To solve the problem . The Interpreter pattern describes how to define a grammar for a simple language , How to express a sentence in the language , And how to explain these sentences .

2. Interpreter pattern structure
The structure of the Interpreter pattern consists of abstract expressions 、 Terminator expression 、 Nonterminal expressions and environment classes make up :
- AbstractExpression( Abstract expression ): Declare an abstract interpretation operation interpret(), Is the base class for all terminator and non terminator expressions ;
- TerminalExpression( Terminator expression ): Terminator is the most basic language unit in the constituent elements of grammar rules , It can't be broken down . The terminator expression implements the interpretation operations related to the terminator in the grammar rules , Each terminator in a sentence is an instance of this class .
- NonterminalExpression( Nonterminal expression ): It realizes the interpretation operation of non terminator in grammar rules , Because non terminator expressions can also contain terminator expressions , So a terminator expression can be a member of a non terminator expression .
- Context( The environment class ): Context class , Used to store some global information outside the interpreter , Usually temporarily store statements that need to be interpreted .

Interpreter mode UML As shown above . Abstract expressions declare abstract interfaces interpret(), Terminator expressions and non terminator expressions implement the interface . among , Of the terminator expression interpret() The interface implements specific interpretation operations , and A non terminal expression may contain a terminal expression or a non terminal expression , So the expression of non Terminator interpret() The interface may call each component recursively interpret() Method .
3. Interpreter pattern code example
In this section, Jungle Use the Interpreter pattern to implement the following small function :
Design a simple interpreter , So that the system can explain 0 and 1 Or operation and and operation ( Regardless of the priority of or operation and and operation , That is, from left to right ), Several examples of statement expressions and output results are shown in the following table :
Example table of expression and output results expression Output results expression Output results 1 and 1 1 0 or 0 0 1 or 1 1 1 and 1 or 0 1 1 or 0 1 0 or 1 and 0 0 1 and 0 0 0 or 1 and 1 or 1 1 0 and 0 0 1 or 0 and 1 and 0 or 0 0
Combined with the structure of the interpreter mode described above and this example , The following roles can be divided :
- Terminator expression role —— Value node (ValueNode):0、1, Because they are the basic elements of expressions , It can't be subdivided
- Terminator expression role —— Operator node (OperatorNode): Operation symbol “and” and “or” , It is also the basic element of an expression
- Nonterminal expression role —— Sentence nodes (SentenceNode): Be similar to “1 and 1” Such an expression or a longer combined expression
- Context class roles —— handler (Handler): Save the input expression and the output result
thus , In this case UML The example is as follows :

3.1. Abstract expression
// Abstract expression classclass AbstractNode{public:AbstractNode(){}// Declare abstract interfacesvirtual char interpret() = 0;};
3.2. Terminator expression role —— Value node
// Terminator expression :ValueNodeclass ValueNode :public AbstractNode{public :ValueNode(){}ValueNode(int iValue){this->value = iValue;}// Implementation of interpretation operationschar interpret(){return value;}private:int value;};
3.3. Terminator expression role —— Operator node
// Terminator expression :OperationNodeclass OperatorNode :public AbstractNode{public:OperatorNode(){}OperatorNode(string iOp){this->op = iOp;}// Implementation of interpretation operationschar interpret(){if (op == "and"){return '&';}else if (op == "or"){return '|';}return 0;}private:string op;};
3.4. Nonterminal expression role —— Sentence nodes
Each sentence node consists of “ Lvalue node + Operator node + Right value node ” form .
// Nonterminal expression :SentenceNodeclass SentenceNode :public AbstractNode{public:SentenceNode(){}SentenceNode(AbstractNode *iLeftNode,AbstractNode *iRightNode, AbstractNode* iOperatorNode){this->leftNode = iLeftNode;this->rightNode = iRightNode;this->operatorNode = iOperatorNode;}char interpret(){if (operatorNode->interpret() == '&'){return leftNode->interpret()&rightNode->interpret();}else{return leftNode->interpret()|rightNode->interpret();}return 0;}private:AbstractNode *leftNode;AbstractNode *rightNode;AbstractNode *operatorNode;};
3.5. Contextual roles —— handler
The processor will process the input expression , And explain the final result of the expression .
// handlerclass Handler{public:Handler(){}void setInput(string iInput){this->input = iInput;}void handle(){AbstractNode *left = NULL;AbstractNode *right = NULL;AbstractNode *op = NULL;AbstractNode *sentence = NULL;string iInput = this->input;vector<string>inputList;char* inputCh = const_cast<char*>(iInput.c_str());char *token = strtok(inputCh, " ");while (token != NULL){inputList.push_back(token);token = strtok(NULL, " ");}for (int i = 0; i < inputList.size() - 2; i += 2){left = new ValueNode(*(inputList[i].c_str()));op = new OperatorNode(inputList[i + 1]);right = new ValueNode(*(inputList[i+2].c_str()));sentence = new SentenceNode(left, right, op);inputList[i + 2] = string(1, sentence->interpret());}string tmpRes = inputList[inputList.size() - 1];if (tmpRes == "1"){result = 1;}else if (tmpRes == "0"){result = 0;}else{result = -1;}this->output();}void output(){printf("%s = %d\n", input.c_str(), result);}private:string input;char result;};
3.6. Client code examples and results
#include <iostream>#include "InterpreterPattern.h"int main(){Handler *handler = new Handler();string input_1 = "1 and 1";string input_2 = "1 and 0";string input_3 = "0 and 1";string input_4 = "0 and 0";string input_5 = "0 or 0";string input_6 = "0 or 1";string input_7 = "1 or 0";string input_8 = "1 or 1";string input_9 = "1 and 0 or 1";string input_10 = "0 or 0 and 1";string input_11 = "1 or 1 and 1 and 0";string input_12 = "0 and 1 and 1 and 1";string input_13 = "0 and 1 and 1 and 1 or 1 or 0 and 1";handler->setInput(input_1); handler->handle();handler->setInput(input_2); handler->handle();handler->setInput(input_3); handler->handle();handler->setInput(input_4); handler->handle();handler->setInput(input_5); handler->handle();handler->setInput(input_6); handler->handle();handler->setInput(input_7); handler->handle();handler->setInput(input_8); handler->handle();handler->setInput(input_9); handler->handle();handler->setInput(input_10); handler->handle();handler->setInput(input_11); handler->handle();handler->setInput(input_12); handler->handle();handler->setInput(input_13); handler->handle();printf("\n\n");system("pause");return 0;}
The operation results are as follows :

4. summary
advantage :
- Easy to change and expand the grammar , Use classes in the interpreter to represent the grammar rules of the language , The grammar can be changed or extended through mechanism classes such as inheritance ;
- Each provision can be represented as a class , So it's easy to implement a simple language ;
- If you want to add a new interpretation expression , Just add a new terminator expression or non terminator expression class , There is no need to change the original code , Comply with opening and closing principle .
shortcoming :
- Complex grammars are difficult to maintain . In the Interpreter pattern, each rule needs to define at least one class , So if a language contains too many rules of grammar , The number of classes will increase significantly , This makes the system difficult to manage and maintain ;
- Inefficient execution , Because there are a lot of loops and recursive calls in the Interpreter pattern .
Apply to the environment :
- Some recurring problems can be expressed in a simple language ;
- The grammar of a language is relatively simple ;
- The interpreter mode can be used regardless of execution efficiency .
边栏推荐
- C # interface holding structure causes packing problem
- Detailed explanation of the underlying principle of concurrent thread pool and source code analysis
- How to design the dead shot, the best and eye-catching performance of the watch Vanguard
- 深入理解MySQL索引凭什么能让查询效率提高这么多?
- steam教育文化传承的必要性
- 开展有效的创客教育课程与活动
- Square array cyclic right shift
- Distributed transaction
- Postgresql源码(56)可扩展类型分析ExpandedObject/ExpandedRecord
- Object to string pit
猜你喜欢

Matplotlib | temperature change visualization

What actions might cause thread context switching?

The solution to the problem of the first screen picture loading flicker

FastCorrect:语音识别快速纠错模型丨RTC Dev Meetup

steam教育文化传承的必要性

14 职责链模式

依图在实时音视频中语音处理的挑战丨RTC Dev Meetup

Eureka的InstanceInfoReplicator类(服务注册辅助工具)

Flask博客实战 - 实现博客的分类管理

Detailed explanation of the underlying principle of concurrent thread pool and source code analysis
随机推荐
JVM memory overflow
学科融合对steam教育的作用
Basic knowledge of DDL operation database and operation table and explanation of use format
安装 MySQL 服务时提示 InstallRemove of the Service Denied
Eureka的InstanceInfoReplicator类(服务注册辅助工具)
Any to Any 实时变声的实现与落地丨RTC Dev Meetup
13 代理模式
Top ten of the year! Saining network security was once again shortlisted in the top 100 report on China's digital security
A simple - timed task component (quartz) -demo
09 组合模式
Matrix operation
Analyzing the role of cognitive theory in maker teacher training
Powerful database design tool PowerDesigner
I spring and autumn web Penetration Test Engineer (elementary) learning notes (Chapter 2)
Five skills to be an outstanding cloud architect
19 备忘录模式
20 状态模式
Bee framework, an ORM framework
Example of multipoint alarm clock
15 命令模式