Twenty-three study notes step by step for the camp .NET design patterns, Interpreter (Interpreter mode)

Outline

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 case, the question sentence is expressed in specific areas under certain grammatical rules, and then build an interpreter to interpret such a sentence, so as to achieve the purpose of solving the problem.

intention

Given a language, which defines a grammar representation, and to define a interpreter, the interpreter uses the representation to interpret sentences in the language.

Structure chart

image

 

Role Description:

AbstractExpression:

- Interpret declare an abstract method abstract syntax tree all nodes must implement the abstract method.

TerminalExpression:

- realization of terminal symbol and grammar associated Interpret method.

- require a TerminalExpression instance at the end of each sentence of the symbol.

NonterminalExpression:

Another implements AbstractExpression class interface for handling syntax tree end nodes Africa. It contains the next AbstractExpression (S) of the reference, it calls the method Interpret each child node.

Context:

Interpreter container information required for the method, the information in terms of globally visible Interpreter. Act as several AbstractExpresssion communication channel between instances.

PatternClient:

Receiving one or build abstract syntax example of the book. For a particular sentence, the syntax tree is often composed of several TerminalExpressions and NonterminalExpression composition. PatterClient under the appropriate context, calls Interpret method.

 

Life examples

In the role of daily life in Chinese and English dictionary is to translate Chinese into English, or to translate English into Chinese, there is a database table to achieve its principle is to first dictionary Curry corresponding Chinese and English, and then to match based on what you type the corresponding outcome.

 

Exemplary embodiment using FIG.

In the company, executives need to apply for a single loan approval, and executives to work and would not have time to sit in front of a computer, the company had a system of employee loan application will be prompted to executives via SMS way, executives can to approve the document by the reply message, executive generally lazy, too reluctant to reply word, only respond to consent or y Y, N or n rejected, instead of a single number by four loan application code, use cases FIG follows:

image

 

Code design

Create ReplyContent.cs:

    /// <summary>
    /// 回复内容
    /// </summary>
    public class ReplyContent
    {
        private string _ReplyText;

        public string ReplyText
        {
            get { return _ReplyText; }
            set { _ReplyText = value; }
        }
    }

 

Then create InterPreter.cs:

    public abstract class InterPreter
    {
        public string ConvertContent(ReplyContent content)
        {
            if (content.ReplyText.Length == 0)
                return "请按规则回复审批短信.";
            return Excute(content.ReplyText);
        }

        public abstract string Excute(string key);
    }

 

Then create Approve.cs:

    public class Approve : InterPreter
    {
        public override string Excute(string key)
        {
            if (key == "Y" || key == "y")
            {
                return "同意";
            }
            else if (key == "N" || key == "n")
            {
                return "拒绝";
            }
            else
            {
                return "回复内容有误,请重新回复.";
            }

        }
    }

 

Then create DocumentNum.cs:

   public class DocumentNum : InterPreter
    {
        public Dictionary<string, string> OddNum
        {
            get
            {
                Dictionary<string, string> OddID = new Dictionary<string, string>();
                OddID.Add("0001", "123890890892345");
                OddID.Add("0002", "123456717012345");
                OddID.Add("0003", "123456669012345");
                OddID.Add("0004", "123423444012345");
                OddID.Add("0005", "123467845345345");
                OddID.Add("0006", "123231234564345");
                OddID.Add("0007", "128797897867745");
                return OddID;
            }
        }

        public override string Excute(string key)
        {
            string value = null;
            if (OddNum.TryGetValue(key, out value))
            {
                return value;
            }
            else
            {
                return "没找到对应的单号.";
            }
        }
    }

 

Then create ReplyClient.cs:

    public class ReplyClient
    {
        public static string ApplyContent(string ReplayValue)
        {
            ReplyContent content = new ReplyContent();
            string approvevalue = ReplayValue.Substring(0, 1);
            string OddIDvalue = ReplayValue.Substring(1, 4);
            string result = string.Empty;
            InterPreter expression = new Approve();
            content.ReplyText = approvevalue;
            result = string.Format("你{0}", expression.ConvertContent(content));
            expression = new DocumentNum();
            content.ReplyText = OddIDvalue;
            result += string.Format("单号是{0}的申请.\n", expression.ConvertContent(content));
            return result;
        }
    }

 

Finally, call:

    public partial class Run : Form
    {
        public Run()
        {
            InitializeComponent();
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            //-------------------------------------
         
             rtbResult.AppendText(ReplyClient.ApplyContent("Y0001"));
             rtbResult.AppendText(ReplyClient.ApplyContent("y0002"));
             rtbResult.AppendText(ReplyClient.ApplyContent("N0003"));
             rtbResult.AppendText(ReplyClient.ApplyContent("n0004"));
            
        }

    }

 

The results as shown below:

image

 

Points achieved

1. Interpreter mode applications is the difficulty Interpreter mode applications, only to meet the "business rules change frequently, and a similar pattern is repeated constantly, and is easy to abstract syntax rules
problem" only suitable for use Interpreter mode.
2. Use Interpreter pattern to represent grammar rules, so you can use object-oriented techniques to easily "extended" grammar.

3. Interpreter mode is more suitable for simple grammar, said grammar representation for complex, Interperter mode will produce a relatively large class hierarchy, need to resort to such a standard tool parser generator.

 

applicability

1. Interpreter mode applications is the difficulty interpreter mode applications, only to meet the "business rules change frequently, and a similar pattern is repeated constantly, and is easy to abstract syntax rules for the issue of" only suitable for use Interpreter mode.

 

to sum up

Interpreter efficiency is not a key issue of concern. The most efficient interpreters usually not directly interpreted by the parse tree implementation, but they are first converted to another form. For example: Regular expressions are typically converted to a state machine. But even in this case, if efficiency is not a critical problem, the converter can still be achieved by Interpreter mode, the model is still useful.

Reproduced in: https: //www.cnblogs.com/springyangwc/archive/2011/05/05/2037146.html

Guess you like

Origin blog.csdn.net/weixin_33716557/article/details/93340900