In-depth design mode-interpreter mode (interpreter pattern)

Source: Internet
Author: User

Mode motive

If a particular type of problem occurs in the system at a very high frequency, consider describing an instance of the problem as a sentence in a language, so you can build an interpreter that solves these problems by interpreting these sentences.
The interpreter pattern describes how to make up a simple language interpreter, mainly used in compilers developed using object-oriented languages.

Pattern definition
Interpreter mode (interpreter pattern): Defines the grammar of the language and creates an interpreter to interpret the sentences in the language, where "language" means code that uses the prescribed format and syntax, which is a class-behaving pattern.
Interpreter Pattern:given A language, define a representation for it grammar along with an interpreter that uses the rep Resentation to interpret sentences in the language.
Frequency of Use:low
UML diagram

Pattern structure
The interpreter pattern contains the following roles:
Abstractexpression: An abstract expression
Terminalexpression: Terminator Expression
Nonterminalexpression: Non-terminator expression
Context: Environment class
Client: Customer Class

Pattern Analysis
The interpreter pattern describes how to define a grammar for a simple language, how to represent a sentence in that language, and how to interpret these sentences.
Examples of grammar rules:
Expression:: = value | Symbol
Symbol:: = expression ' + ' expression | Expression '-' expression
Value:: = an integer//integer value
Some symbols can be used to represent different meanings in grammar rule definitions, such as using the "|" Represents or, using "{" and "}" to represent a combination, using "*" means 0 or more occurrences, where the most frequently used symbol is the "|" of the representation or relationship.

Abstract Syntax Tree:
In addition to using grammatical rules to define a language, in the interpreter pattern, it is possible to visually represent the composition of a language in a graphical way called an abstract Syntax tree, an AST, and each abstract syntax tree corresponds to a language instance.

Abstract syntax tree describes how to form a complex sentence, through the analysis of the abstract syntax tree, can identify the language of the Terminator and non-Terminator class.
In the interpreter mode, each of the Terminator and non-Terminator have a specific class corresponding to it, because the use of classes to represent each syntax rule, so that the system has a good scalability and flexibility.

Pattern Instances and parsing
Introducing the interpreter pattern in the English-Chinese translation system as an example
System structure

Abstractexpression Interface IExpression.cs

using System.Text; namespace interpreterpattern{    // define Abstractexpression interface    interface  Iexpression    {        void  interpret (StringBuilder sb);    }}

Specific expression WordExpression.cs

usingSystem.Text;namespaceinterpreterpattern{//define the specific expression, which includes the translation of the English words and the translation of the English period.      Public classwordexpression:iexpression {Private string_value;  PublicWordexpression (stringvalue) {_value=value; }         Public voidinterpret (StringBuilder SB) {sb. Append (Chineseenglishdict.getenglish (_value.        ToLower ())); }    }}


usingSystem.Text;namespaceinterpreterpattern{//translation of the English period     Public classsymbolexpression:iexpression {Private string_value;  PublicSymbolexpression (stringvalue) {             This. _value =value; }         Public voidinterpret (StringBuilder sb) {Switch(_value) { Case ".": SB. Append (". ");  Break; }        }    }}

Context: Environment class ChineseEnglishDict.cs

usingSystem.Collections.Generic;namespaceinterpreterpattern{ Public Static classchineseenglishdict {Private Staticdictionary<string,string> _dictory =Newdictionary<string,string>(); Staticchineseenglishdict () {_dictory. ADD (" This","it"); _dictory. ADD (" is","is a"); _dictory. ADD (" an","a"); _dictory. ADD ("Apple","Apple"); }         Public Static stringGetenglish (stringvalue) {            return_dictory[value]; }    }}

Assemble each part of the interpreter to be packaged to make it easy for users to call Translator.cs.

usingSystem;usingSystem.Collections.Generic;usingSystem.Text;namespaceinterpreterpattern{//each part of the interpreter is combined to be packaged for easy user invocation.      Public Static classTranslator { Public Static stringTranslate (stringsentense) {StringBuilder SB=NewStringBuilder (); List<IExpression> expressions =NewList<iexpression>(); string[] elements = sentense. Split (New Char[] {'.'}, Stringsplitoptions.removeemptyentries); foreach(stringElementinchelements) {                string[] Words = element. Split (New Char[] {' '}, Stringsplitoptions.removeemptyentries); foreach(stringWordinchwords) {Expressions. ADD (Newwordexpression (word)); } expressions. ADD (NewSymbolexpression (".")); }            foreach(Iexpression expressioninchexpressions) {expression.            Interpret (SB); }                            returnsb.        ToString (); }    }}

Client: Customer Class

 using   System;  namespace   interpreterpattern{ class   program { static  void  Main (string  [] args) { string Englist =  this is a apple.   "             string  Chinese = Translator.translate (            Englist);            Console.WriteLine (Chinese); (); }    }}

Model Pros and cons
Advantages of the Interpreter mode
Easy to change and expand grammar.
Easy to implement grammar.
Added a new way to interpret the expression.
Disadvantages of the Interpreter mode
Difficult to maintain for complex grammars.
less efficient execution.
The application scenario is limited.

Mode applicable environment
You can use the interpreter mode in the following situations:
You can represent a sentence in a language that needs to interpret execution as an abstract syntax tree.
Some recurring problems can be expressed in a simple language.
Grammar is relatively simple.
Efficiency is not a key issue.

"Statement and thanks"
This article, on the shoulders of many giants, draws on and cites many other works or writings that others have copyrighted, and is here to thank the former people for their contributions. And at the same time publish the quoted content, the original author or source (some of the content from the Internet can not be traced to the source, deeply regret).

Design mode-the basis of reusable object-oriented software author: [US] Erich gamma/richard Helm/ralph johnson/john vlissides Translator: Li Yingjun/Ma Xiaoxing/Cai Min/Liu Jianzhong and other machinery industry press
Refactoring-Improving the design of existing code author: Martin Fowler Translator: China Power Press, HOU-jie
"Agile software Development-principles, patterns and practices" Author: Robert C. Martin Tsinghua University Press
"Programmer's path to cultivation-from small to expert" by Andrew hunt/david Thomas Electronics Press
Head First design mode author: Freeman translator: O ' Reilly Taiwan company China Power Press
"Zen of Design Pattern" Author: Qin Xiaobo Machinery Industry Press
MSDN Webcast "C # Object-oriented design mode discussion on" lecturer: Li Jianzhong
Liu wei. design mode. Beijing: Tsinghua University Press, 2011.
Liu wei. Design pattern Training Tutorial. Beijing: Tsinghua University Press, 2012.
"Big Liar design Mode" Author: Geoscience Tsinghua University Press
C # Illustrated Tutorial Author: Solis Translator: Surin/Zhu Ye People's post and telecommunications press
"You must know. NET" Author: Wang Tao
. NET in Project author: Li Tianping Electronics Press
The Microsoft. NET Enterprise Application Architecture Design Author: (US) Esposito and other translators: Chen Lifu NET Design Patterns
Http:// Blog Lu Zhenyu
Http:// Blog Li Huijun Anlyren
Http:// Blog Idior
Http:// blog Allen Lee
HTTP://BLOG.CSDN.NET/AI92 Blog ai92 Zhang Lovecherry

In-depth design mode-interpreter mode (interpreter pattern)

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: 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.