preface

Today we are going to look at the Interpreter Pattern. How do you interpret this Pattern? A simple example, what is the role of the English translator? Translate unknown English into Chinese for easy understanding, or translate Chinese into English for use. The purpose is to translate and explain the language to facilitate understanding and use. What about the interpreter pattern? The pattern implements an expression interface that interprets a particular context. Mainly for some fixed grammar to build an interpreter to explain sentences.

Introduction to interpreter patterns

A, the other

In software systems, suspicious patterns are repeated if there are specific domain problems that are complex. This use of generic programming methods makes coding extremely frequent. In such cases, the domain-specific problem is transformed into a sentence that expresses certain grammatical rules. Build an interpreter to interpret such sentences to solve the problem.

Second, the intention

Given a language, define its grammatical representation and define an interpreter that uses the identifier to interpret sentences in the language.

3. Case diagram

Interpreter mode code examples

Take a look at the case chart above and let’s take a look at the five parts:

Abstract expressions: Define interpreter interfaces, convention operations. The Interpret interface is specifically used to implement the functions of the interpreter

Terminal expressions: Each terminal in an interface or grammar that implements an abstract expression has its own specific terminal expression.

Non-terminal expressions: Each rule in a grammar requires a specific non-terminal expression, an operator in a general representation grammar, or some keywords.

Context class: This role is used to store the specific location of the terminator.

Client: the client that uses the interpreter.

Let’s take a look at such a case, in the daily program development occasionally encountered Chinese to Arabic numerals. For some operations, conversion from Chinese to numeric is required. Let’s see how this can be resolved:

namespace Interpreter_Pattern { class InterpreterPattern { } /// <summary> /// Context: /// </summary> public class Context {private string _Statement; public Context(string statement) { this._statement = statement; contextMap.Add("一", 1);
            contextMap.Add("二", 2);
            contextMap.Add("Three", 3);
            contextMap.Add("Four", 4);
            contextMap.Add("Five", 5);
            contextMap.Add("Six", 6);
            contextMap.Add("Seven", 7);
            contextMap.Add("Eight"And 8); contextMap.Add("Nine", 9);
        }
        public string Statement
        {
            get { return this._statement; }
            set{ this._statement = value; } } public Dictionary<string, int> contextMap = new Dictionary<string, int>(); } /// <summary> /// AbstractExpression: Abstract expression /// </summary> public abstract class AbstractExpression {public abstract void Interpret(Context Context); } public class TerminalExpression : AbstractExpression { public override void Interpret(Context context) {if(context.Statement! =null) { foreach (var Keyin context.contextMap.Keys)
                {
                    if(context.Statement.Contains(Key)) { context.Statement= context.Statement.Replace(Key, context.contextMap[Key].ToString()); // context.contextMap[Key]); / /}}}return context;
        }
    }

    public class NonterminalExpression : AbstractExpression
    {
        public override void Interpret(Context context)
        {
            if (context.Statement.Contains("Add"))
            {
                context.Statement= context.Statement.Replace("Add"."+");
            }
            if (context.Statement.Contains("Cut"))
            {
                context.Statement= context.Statement.Replace("Cut"."-");
            }
            if (context.Statement.Contains("Take"))
            {
                context.Statement= context.Statement.Replace("Take"."*");
            }
            if (context.Statement.Contains("In addition to"))
            {
                context.Statement= context.Statement.Replace("In addition to"."/"); } / /returncontext; }}}Copy the code

namespace Interpreter_Pattern
{
    class Program
    {
        static void Main(string[] args)
        {
            Context context = new Context("Three plus eight plus nine minus two times five over three."); AbstractExpression abstractExpression = new TerminalExpression(); abstractExpression.Interpret(context); AbstractExpression noabstractExpression = new NonterminalExpression(); noabstractExpression.Interpret(context); Console.WriteLine(context.Statement); }}}Copy the code

Usage scenarios and advantages and disadvantages

First, use scenarios

A sentence in a language that needs to be interpreted can be represented as an abstract syntax tree.

2. Some repetitive questions can be expressed in a simple language.

3. When the grammar of the language is relatively simple, it can be considered

Second, the advantages of

1. High scalability and flexibility.

2. A new way to interpret expressions is added to make it more convenient.

3. Easy to implement simple grammar.

Three and disadvantages

1. Less available scenarios.

2. Grammar maintenance for replication is difficult.

Interpreter schema causes class bloat.

conclusion

Now that we’re done with the interpreter pattern, let’s think a little bit about regular expressions. Regular expressions are also a typical interpreter. The interpreter pattern is the definition of the representation and interpreter for a given language. The interpreter is then used to interpret sentences in the language. Interpreter mode in the ordinary use of less, generally used for expression calculation or compiler, SQL statement parsing. So far we have covered 23 design patterns. We can do a general review with the first article in this series.

Live with love and you will make yourself happy! Work with love and you will make a lot of people happy!

Please scan the qr code below and join me on the road to design mode!