I understand the design pattern (C ++ implementation) -- interpreter Pattern)

Source: Internet
Author: User
Overview:

In the future, machine intelligence has become a trend. Now, mobile phones can understand English and Mandarin. The intelligence of tens of thousands of dialects in Greater China may also be a trend. Although our dialects are similar to those in Mandarin, but it is still different. This may require a new syntax analyzer to help us.

Our interpreter mode describes how to define a grammar for a simple language, how to represent a sentence in the language, and how to explain these sentences.

However, interpreting a natural language is a complex process. Let's take the addition and subtraction operation as an example to explain the interpreter mode in detail.

Class diagrams and instances:

Abstract Expression role(Abstractexpression): declares an abstract interpreted operation, which must be implemented by all specific expression roles.
Terminator expression role(Terminalexpression ): Implement interpreted operations associated with elements in grammar. Generally, there is only one Terminator expression in a interpreter mode, but multiple instances correspond to different Terminators,
Terminator is the basic element used in the language and cannot be decomposed. For example, X-> Xa. Here, a is a Terminator, because no other rule can change a to another symbol, however, X can be changed to another symbol, So X is not a Terminator.
Non-terminator expression role(Nonterminalexpression): Each rule in a grammar corresponds to a non-terminator expression. A non-terminator expression increases based on the complexity of the logic. In principle, each grammar rule corresponds to a non-terminator expression.
Environment role(Context): Contains global information other than the interpreter.

Instance:

#include <iostream>  #include <map>  #include <string>   using namespace std;  class Context{private:map<string, int> valueMap;public:void addValue(string key,int value){       valueMap.insert(std::pair<string,int>(key,value));}int getValue(string key){return valueMap[key];}};class AbstractExpression{public : virtual int interpreter(Context context) = 0;};class AddNonterminalExpression : public AbstractExpression{private :AbstractExpression *left;AbstractExpression *right;public:AddNonterminalExpression(AbstractExpression *left, AbstractExpression *right){this->left = left;this->right = right;}int interpreter(Context context){return this->left->interpreter(context) + this->right->interpreter(context);}};class SubtractNonterminalExpression : public AbstractExpression{private :AbstractExpression *left;AbstractExpression *right;public:SubtractNonterminalExpression(AbstractExpression *left, AbstractExpression *right){this->left = left;this->right = right;}int interpreter(Context context){return this->left->interpreter(context) - this->right->interpreter(context);}};class TerminalExpression : public AbstractExpression{private :int i;public :TerminalExpression(int i){this->i = i;}int interpreter(Context context){return this->i;}};int main(){  //a-b+cContext context;context.addValue("a", 7);context.addValue("b", 8);context.addValue("c", 2);SubtractNonterminalExpression *subtractValue = new SubtractNonterminalExpression(new TerminalExpression(context.getValue("a")), new TerminalExpression(context.getValue("b")));AddNonterminalExpression *addValue = new AddNonterminalExpression(subtractValue, new TerminalExpression(context.getValue("c")));cout<< addValue->interpreter(context);return 0;  }  
Applicability:

The interpreter mode can be considered in the following cases:

(1) sentences in a language to be interpreted and executed can be expressed as an abstract syntax tree.

(2) repeated problems can be expressed in a simple language.

(3) the syntax of a language is relatively simple.

(4) execution efficiency is not a key issue. (Note: efficient interpreters are generally not implemented by directly interpreting the abstract syntax tree. Instead, they need to be converted into other forms, and the execution efficiency in the interpreter mode is not high .)

Advantages and disadvantages:

(1) easy to change and extend grammar. Because classes are used in the interpreter mode to represent the grammar rules of a language, you can use inheritance or other mechanisms to change or extend the syntax.

(2) Each grammar rule can be expressed as a class, so a simple language can be conveniently implemented.

(3) It is easier to implement grammar. In the abstract syntax tree, the implementation of each expression node class is similar. The code writing of these classes is not very complex. You can also use some tools to automatically generate node class code.

(4) It is more convenient to add new interpretation expressions. If you want to add a new interpreted expression, you only need to add a new Terminator expression or non-terminator expression class. The code of the original expression class does not need to be modified and complies with the "open and closed principle ".

Disadvantages:

(1) difficult to maintain complex grammar. In the interpreter mode, each rule must define at least one class. Therefore, if a language contains too many grammar rules, the number of classes will increase dramatically, making it difficult for the system to manage and maintain them, in this case, you can consider replacing the interpreter mode with a syntax analysis program.

(2) execution efficiency is low. Because a large number of loops and recursive calls are used in the interpreter mode, the speed of interpreting complicated sentences is very slow, and the code debugging process is also troublesome.

Overview:

Try not to use the interpreter mode in important modules because of difficult maintenance. In a project, you can use the script language to replace the interpreter mode.

Lcl_data was originally created in csdn. Net [http://blog.csdn.net/lcl_data/article/details/9259905]

For other design patterns, see:Design patterns I understand

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.