C # Design Patterns study notes: (23) interpreter mode

    This excerpt from the note: https://www.cnblogs.com/PatrickLiu/p/8242238.html , learning about the recording for subsequent lookup.

    I. Introduction

    Today we talk about the eleventh mode behavioral design patterns - the interpreter mode and final mode of object-oriented design patterns. Must first explain, in fact, this model is not the last die

Type (ordered by Gof terms), why put it in the end it? Because we write an interpreter in a business opportunity system is not a lot less practice, understanding and application of the model a bit sleepy

Difficult, so I put it last, starting with the name of view this model. Like "interpreter" and Google's English translation, suppose one day you travel to foreign countries such as the United States, if you do not speak English too

Do not understand, communication is a big obstacle, it is estimated will not enjoy a good time, because there are many attractions that you may not understand the explanation (without Chinese translation, in general, there will be). so we

Need a translation software (such as IFLYTEK), you can put the English translation, that each other can better understand each other's meaning. Personally feel that translation software can also be regarded as an interpreter, you do not

Understand interpreted as you can understand. We write code, we need a compiler to write code that can be compiled into machine language understood by the machine, this aspect is concerned, C # compiler is also an interpreter.

    Second, the mode explains Introduction

    Interpreter pattern: English name --Interpreter Pattern; classification - type behavior.

    2.1, motivation (Motivate)

    In the software build process, if the problem is more complex in a particular area, a similar pattern is repeated constantly, if you use common programmatic way to achieve will face very frequent changes. In this kind of

Case, the problem is specific area expressed as the sentence under certain rules of grammar, and then build an interpreter to interpret such sentences, so as to achieve the purpose of solving the problem.

    2.2, intent (Intent)

    Given a language, which defines a grammar representation, and to define a interpreter, the interpreter uses the representation to interpret sentences in the language. - "Design Patterns" GoF

    2.3, the structure of FIG. (Structure)

    2.4 the composition, mode

    As can be seen, the following roles in the structure of FIG interpretation mode:

    1) Abstract expression (AbstractExpression): defined interpreter interface conventions explaining the operation of the interpreter. Interpret the interface which, as its name implies, it is designed to explain the de

Interpreter to be achieved function.

    2) terminator expression (Terminal Expression): abstract interface to achieve the desired character expression, primarily a Interpret () method. Each grammar has a specific end terminator

Correspondingly junction expression. There is a simple formula such as R = R1 + R2, in which R1 and R2 is a terminator, the corresponding analytical R1 and R2 is interpreter terminator expression.

    3) nonterminals expression (Nonterminal Expression): each grammar rule requires a particular nonterminal expression, typically expression is nonterminals in the grammar or operator

Other keywords, such as the formula R = R1 + R2, the "+" is nonterminal analysis "+" interpreter is a nonterminal expression.

    4) Environmental role (Context): this role is generally used to store task grammar specific value corresponding to the respective terminal symbols, such as R = R1 + R2, we assign to R1 100, 200 assigned to R2. This

Some information needs to be stored into the environment role, in many cases we use the Map to serve as environmental role is sufficient.

    5) The client (Client): refers to the client using an interpreter, here generally done in accordance with the syntax of the language expression into an abstract syntax tree using the objects described in the interpreter, then call Solutions

Release operation.

    2.5 specific implementation, the mode explains

    In many occasions the need to convert numbers to Chinese, we can use the interpreter to achieve this, the explanation given digital representation of characters into a grammatical norms, codes are as follows:

    class Program 
    { 
        ///  <Summary> 
        /// environmental context
         ///  </ Summary> 
        public  Sealed  class the Context 
        { 
            public  String the Statement { GET ; SET ;} 

            public  int the Data { GET ; SET ;} 

            public the Context ( String Statement) 
            { 
                the Statement = Statement; 
            } 
        } 

        ///  <Summary> 
        /// abstract expression
        /// </summary>
        public abstract class Expression
        {
            protected Dictionary<string, int> table = new Dictionary<string, int>(9);

            protected Expression()
            {
                table.Add("", 1);
                table.Add("", 2);
                table.Add("", 3);
                table.Add("", 4);
                table.Add("", 5);
                table.Add("", 6);
                table.Add("", 7);
                table.Add("", 8);
                table.Add("", 9);
            }

            public virtual void Interpreter(Context context)
            {
                if (context.Statement.Length == 0)
                {
                    return;
                }

                foreach (string key in table.Keys)
                {
                    int value = table[key];

                    if (context.Statement.EndsWith(key + GetPostFix()))
                    {
                        context.Data += value * Multiplier();
                        context.Statement = context.Statement.Substring(0, context.Statement.Length -A GetLength ()); 
                    } 
                    IF (context.Statement.EndsWith ( " zero " )) 
                    { 
                        context.Statement = context.Statement.Substring ( 0 , context.Statement.Length - . 1 ); 
                    } 
                } 
            } 

            public  abstract  String getPostfix () ; 

            public  abstract  int Multiplier (); 

            // tens, hundreds, thousands of bits used, so use virtual methods. 
            public  Virtual  int a GetLength () 
            { 
                return GetPostFix().Length + 1;
            }
        }

        /// <summary>
        /// 个位表达式
        /// </summary>
        public sealed class GeExpression : Expression
        {
            public override string GetPostFix()
            {
                return "";
            }

            public override int Multiplier()
            {
                return 1;
            }

            public override int GetLength()
            {
                return . 1 ; 
            } 
        } 

        ///  <Summary> 
        /// ten expression
         ///  </ Summary> 
        public  Sealed  class ShiExpression: the Expression 
        { 
            public  the override  String getPostfix () 
            { 
                return  " ten " ; 
            } 

            public  the override  int Multiplier () 
            { 
                return  10 ; 
            } 
        } 

        ///  <Summary> 
        /// one hundred expression
         ///  </ Summary>
        public sealed class BaiExpression : Expression
        {
            public override string GetPostFix()
            {
                return "";
            }

            public override int Multiplier()
            {
                return 100;
            }
        }

        /// <summary>
        /// 千位表达式
        /// </summary>
        public sealed class QianExpression : Expression
        {
            public override string GetPostFix()
            {
                return "";
            }

            public override int Multiplier()
            {
                return 1000;
            }
        }

        /// <summary>
        /// 万位表达式
        /// </summary>
        public sealed class WanExpression : Expression
        {
            public override string GetPostFix()
            {
                return "";
            }

            public override int Multiplier()
            {
                return 10000;
            }

            public override int GetLength()
            {
                return 1;
            }

            public override void Interpreter(Context context)
            {
                if (context.Statement.Length == 0)
                {
                    return;
                }

                ArrayList tree = new ArrayList
                {
                    new GeExpression(),
                    new ShiExpression(),
                    new BaiExpression(),
                    new QianExpression()
                };

                foreach (string key in table.Keys)
                {
                    if (context.Statement.EndsWith(GetPostFix()))
                    {
                        int temp = context.Data;
                        context.Data = 0;

                        context.Statement = context.Statement.Substring(0, context.Statement.Length - GetLength());

                        foreach (Expression exp in tree)
                        {
                            exp.Interpreter(context);
                        }
                        context.Data = temp + context.Data * Multiplier();
                    }
                }
            }
        }

        /// <summary>
        /// 亿位表达式
        /// </summary>
        public sealed class YiExpression : Expression
        {
            public override string GetPostFix()
            {
                return "亿";
            }

            public override int Multiplier()
            {
                return 100000000;
            }

            public override int GetLength()
            {
                return 1;
            }

            public override void Interpreter(Context context)
            {
                ArrayList tree = new ArrayList
                {
                    new GeExpression(),
                    new ShiExpression(),
                    new BaiExpression(),
                    new QianExpression()
                };

                foreach (string key in table.Keys)
                {
                    if (context.Statement.EndsWith(GetPostFix()))
                    {
                        int temp = context.Data;
                        context.Data = 0;
                        context.Statement = context.Statement.Substring(0, context.Statement.Length - GetLength());

                        foreach (Expression exp in tree)
                        {
                            exp.Interpreter(context);
                        }
                        context.Data = TEMP + context.Data * Multiplier (); 
                    } 
                } 
            } 
        } 

        static  void the Main ( String [] args) 
        { 
            #region interpretation mode
             @ Decomposition: ((five million)) ((seven thousand) (iii one hundred) (zero) (ii) million) ((six thousand) (four hundred) (fifty) (ii)) 
            String Roman = " 573,026,452 " ; 

            Context context = new new the context (Roman); 
            the ArrayList Tree = new new the ArrayList 
            { 
                new new GeExpression(),
                new ShiExpression(),
                new BaiExpression(),
                new QianExpression(),
                new WanExpression(),
                new YiExpression()
            };

            foreach (Expression exp in tree)
            {
                exp.Interpreter(context);
            }

            Console.Write(context.Data);

            Console.Read();
            #endregion
        }
    }
View Code

    Results are as follows:

    Third, to achieve point mode interpreter

    Use Interpreter pattern to represent grammar rules, so you can use object-oriented techniques to easily "extended" grammar.

    Interpreter pattern comparison for simple grammar, said grammar represent complex, Interpreter mode a relatively large class hierarchy, need to resort to such a standard parser generator

tool.

    The main advantage of 3.1 to explain the mode of

    1) easy to change and extend the grammar.

    2) Each provisions of law rules can be represented as a class, so it can easily implement a simple language.

    3) realization of grammar more easily. In the abstract syntax tree is similar to the implementation of each expression node class, write code for these classes are not particularly complex, but also through some of the tool automatically generates

Class code to the node.

    4) Add a new interpretation of the expression is more convenient. If you need to add new interpretation requires only a corresponding increase in the expression of a new terminator or non-terminator expression based expression, the expression of the original class code

Without modification, in line with "the principle of opening and closing."

 The main drawback of 3.2 to explain the mode of

    1) For complex grammars difficult to maintain. In interpreter mode, each rule at least need to define a class, so if a language contains too many grammar rules, the number of classes will be increased dramatically, resulting in

Difficult to manage and maintain the system, then you can consider using other means parser instead interpreted mode.

    2) the lower the efficiency. Since a large number of cycles and a recursive call mode in the interpreter, so it is very slow in the interpretation of more complex sentences, and code debugging process is relatively cumbersome.

    3.3, in the case of the following mode may be considered using an interpreter,

    Interpreter mode applications is the difficulty Interpreter mode applications, only to meet the "business rules change frequently, and a similar pattern constantly repeats the same time easy to abstract syntax rules for the issue of"

It is suitable for use Interpreter mode.

    1) When an interpreted language needs, and can be expressed in the language of the sentence as an abstract syntax tree, consider using an interpreter mode (such as an XML document explains, in areas such as regular expressions

area)

    2) Some recurring problem can be a simple language to express.

    3) a language grammar is relatively simple.

    4) When a problem is not the key to efficiency and can be considered a major concern interpreter mode (Note: The effective interpreter is not usually accomplished by direct interpretation of abstract syntax tree, but they need to be converted

Into other forms, using an interpreter mode execution efficiency is not high. )

    Attaining the interpretation mode of .NET

    Regular expression is a typical interpreter. When ASP.NET, the aspx file into dll, html language will be processed, this process also includes a mode in which the interpreter.

Interpreter model is actually the shadow of the Composite pattern, but their problem is not the same.

    V. Summary

    So far, 23 design patterns are finished. Interpreter mode and other modes can be mixed, and the use of specific methods to solve the problems I've listed a table, we try to understand, perhaps for large

Some help at home, listed below:

    (1) and a combined mode interpreter

    These two can be combined, typically nonterminal interpreter objects combination mode corresponding to the combination, terminators, leaf objects corresponding to the interpreter.

    (2) interpretation mode and iterative mode

    Since the interpreter mode is typically implemented using a combination of patterns, so when traversing the entire object structure, using an iterative mode.

    (3) interpretation mode and Flyweight

    When using an interpreter model, may cause a plurality of fine-grained objects, such as a variety of terminator interpreter, the interpreter of the terminator is a different expression of the same, can be shared

And therefore it can be introduced Flyweight to share these objects.

    (4) and a visitor pattern interpretation mode

    Mode in the interpreter, the interpreter and syntax rules corresponding relationship of the object is. Change means that changes the function of grammar rules, will naturally lead to different objects using an interpreter, and a grammar rule can

It is to be interpreted differently interpreted. So when building an abstract syntax tree, if each node corresponding interpreter objects are fixed, which means that the node corresponding function is fixed, then

We had to build different abstract syntax tree as needed. To make the abstract syntax tree construction is more common, it is required to explain the function of the not so fixed, to be able to easily change the function of the interpreter,

This time becomes how you can easily change the tree node object function, and visitors can be a good model to achieve this function.

Guess you like

Origin www.cnblogs.com/atomy/p/12345743.html