Overview
In the process of software building, if the problems in a specific field are complicated and similar models are repeated, the implementation of common programming methods will face frequent changes. In this case, the problem in a specific field is expressed as a sentence under a certain syntax rule, and then an interpreter is constructed to explain such a sentence, so as to solve the problem.
Intention
Given a language, it defines a syntax expression and an interpreter that uses this representation to interpret sentences in the language.
Structure chart
Role description:
AbstractExpression:
-Declare an abstract Interpret method. All nodes in the abstract syntax tree must implement this abstract method.
TerminalExpression:
-Implement the Interpret method related to the end symbol in the syntax.
-A TerminalExpression instance is required in the end symbol of each sentence.
NonterminalExpression:
In additionAbstractExpressionInterface Class, used to process the syntax of non-terminal nodes in the syntax tree. It contains the nextAbstractExpressionCall the Interpret method of each subnode.
Context:
Container of the information required by the Interpreter method, which is globally visible to Interpreter. Act as severalAbstractExpresssionCommunication channels between instances.
PatternClient:
Construct or receive an example of an abstract syntax. For a specific sentence, the syntax tree is usually composed of several TerminalExpressions and NonterminalExpression. In the appropriate context, the PatterClient calls the Interpret method.
Examples in life
In daily life, the English-Chinese dictionary is used to translate Chinese into English or Chinese. Its implementation principle is that the dictionary first stores the corresponding Chinese and English in the database table, then match the result based on your input.
Example
In a company, an application for a loan order requires approval from an executive, and an executive does not sit in front of a computer during work hours. The company has a system, when an employee applies for a loan, he or she will send a text message via the mobile phone to notify the Executive. The executive can reply to the text message to approve the document. The Executive is generally lazy and does not want to reply too many words, you can only reply to Y or y for consent, N or n for rejection, and use the four-digit identification code to replace the borrow application number. The example is shown below:
Code Design
Create ReplyContent. cs First:
Html # viewSource "commandName =" viewSource "highlighterId =" highlighter_166603 "> view sourceprint?
04 |
public class ReplyContent |
06 |
private string _ReplyText; |
08 |
public string ReplyText |
10 |
get { return _ReplyText; } |
11 |
set { _ReplyText = value; } |
Create InterPreter. cs again:
View sourceprint