解释器模式(Interpreter Pattern)

设计模式 - 吕震宇

.NET设计模式系列文章

薛敬明的专栏

乐在其中设计模式(C#)


设计模式16:Interpreter Pattern(解释者模式)

本文翻译自:http://www.dofactory.com/Patterns/PatternInterpreter.aspx

Define:Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.

一、解释者模式概念

针对某一编程语言,为其语法定义一定的描述语言和解释器,解释器利用描述语言去解释该编程语言中的所有语法。

二、UML类图

 
UML

三、参与者

该模式的类/对象参与者包括:

  • AbstractExpression  (描述)
    • 为执行operation()声明一个接口
  • TerminalExpression  ( ThousandExpression, HundredExpression, TenExpression, OneExpression )
    • 在语法中使用终止符实现一个operation解释器
    • 在语句中要求所有终止符需要一个实例
  • NonterminalExpression  ( 不使用 )
    • one such class is required for every rule R ::= R1R2...Rn in the grammar
    • maintains instance variables of type AbstractExpression for each of the symbols R1 through Rn.
    • implements an Interpret operation for nonterminal symbols in the grammar. Interpret typically calls itself recursively on the variables representing R1 through Rn.
  • Context  (Context)
    • 所有全局解释器的内容信息
  • Client  (InterpreterApp)
    • builds (or is given) an abstract syntax tree representing a particular sentence in the language that the grammar defines. The abstract syntax tree is assembled from instances of the NonterminalExpression and TerminalExpression classes
    • invokes the Interpret operation

    四、示例代码

    以下结构性的代码描述解释器模式,即利用一个定义好的语法,为进程解析声明提供解释器。

     

    [c-sharp] view plain copy
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5. using System.Collections;  
    6.   
    7. namespace Interpreter_Pattern  
    8. {  
    9.     /// <summary>  
    10.   
    11.     /// MainApp startup class for Structural   
    12.   
    13.     /// Interpreter Design Pattern.  
    14.   
    15.     /// </summary>  
    16.   
    17.     class MainApp  
    18.     {  
    19.   
    20.         /// <summary>  
    21.   
    22.         /// Entry point into console application.  
    23.   
    24.         /// </summary>  
    25.   
    26.         static void Main()  
    27.         {  
    28.   
    29.             Context context = new Context();  
    30.   
    31.             // Usually a tree   
    32.   
    33.             ArrayList list = new ArrayList();  
    34.   
    35.   
    36.             // Populate 'abstract syntax tree'   
    37.   
    38.             list.Add(new TerminalExpression());  
    39.   
    40.             list.Add(new NonterminalExpression());  
    41.   
    42.             list.Add(new TerminalExpression());  
    43.   
    44.             list.Add(new TerminalExpression());  
    45.   
    46.   
    47.   
    48.             // Interpret  
    49.   
    50.             foreach (AbstractExpression exp in list)  
    51.             {  
    52.   
    53.                 exp.Interpret(context);  
    54.   
    55.             }  
    56.   
    57.   
    58.   
    59.             // Wait for user  
    60.   
    61.             Console.ReadKey();  
    62.   
    63.         }  
    64.   
    65.     }  
    66.   
    67.   
    68.   
    69.     /// <summary>  
    70.   
    71.     /// The 'Context' class  
    72.   
    73.     /// </summary>  
    74.   
    75.     class Context  
    76.     {  
    77.   
    78.     }  
    79.   
    80.   
    81.   
    82.     /// <summary>  
    83.   
    84.     /// The 'AbstractExpression' abstract class  
    85.   
    86.     /// </summary>  
    87.   
    88.     abstract class AbstractExpression  
    89.     {  
    90.   
    91.         public abstract void Interpret(Context context);  
    92.   
    93.     }  
    94.   
    95.   
    96.   
    97.     /// <summary>  
    98.   
    99.     /// The 'TerminalExpression' class  
    100.   
    101.     /// </summary>  
    102.   
    103.     class TerminalExpression : AbstractExpression  
    104.     {  
    105.   
    106.         public override void Interpret(Context context)  
    107.         {  
    108.   
    109.             Console.WriteLine("Called Terminal.Interpret()");  
    110.   
    111.         }  
    112.   
    113.     }  
    114.   
    115.   
    116.   
    117.     /// <summary>  
    118.   
    119.     /// The 'NonterminalExpression' class  
    120.   
    121.     /// </summary>  
    122.   
    123.     class NonterminalExpression : AbstractExpression  
    124.     {  
    125.   
    126.         public override void Interpret(Context context)  
    127.         {  
    128.   
    129.             Console.WriteLine("Called Nonterminal.Interpret()");  
    130.   
    131.         }  
    132.   
    133.     }  
    134. }  

    另外一个实例即利用解释器模式来实现如何将罗马数字跟十进制的转换,代码如下:

    [c-sharp] view plain copy
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5. using System.Collections;  
    6.   
    7. namespace Interpreter_Pattern  
    8. {  
    9.     class MainApp  
    10.     {  
    11.   
    12.         /// <summary>  
    13.   
    14.         /// Entry point into console application.  
    15.   
    16.         /// </summary>  
    17.   
    18.         static void Main()  
    19.         {  
    20.   
    21.             string roman = "MCMXXVIII";  
    22.   
    23.             Context context = new Context(roman);  
    24.   
    25.   
    26.   
    27.             // Build the 'parse tree'  
    28.   
    29.             List<Expression> tree = new List<Expression>();  
    30.   
    31.             tree.Add(new ThousandExpression());  
    32.   
    33.             tree.Add(new HundredExpression());  
    34.   
    35.             tree.Add(new TenExpression());  
    36.   
    37.             tree.Add(new OneExpression());  
    38.   
    39.   
    40.   
    41.             // Interpret  
    42.   
    43.             foreach (Expression exp in tree)  
    44.             {  
    45.   
    46.                 exp.Interpret(context);  
    47.   
    48.             }  
    49.   
    50.   
    51.   
    52.             Console.WriteLine("{0} = {1}",  
    53.   
    54.               roman, context.Output);  
    55.   
    56.   
    57.   
    58.             // Wait for user  
    59.   
    60.             Console.ReadKey();  
    61.   
    62.         }  
    63.   
    64.     }  
    65.   
    66.   
    67.   
    68.     /// <summary>  
    69.   
    70.     /// The 'Context' class  
    71.   
    72.     /// </summary>  
    73.   
    74.     class Context  
    75.     {  
    76.   
    77.         private string _input;  
    78.   
    79.         private int _output;  
    80.   
    81.   
    82.   
    83.         // Constructor  
    84.   
    85.         public Context(string input)  
    86.         {  
    87.   
    88.             this._input = input;  
    89.   
    90.         }  
    91.   
    92.   
    93.   
    94.         // Gets or sets input  
    95.   
    96.         public string Input  
    97.         {  
    98.   
    99.             get { return _input; }  
    100.   
    101.             set { _input = value; }  
    102.   
    103.         }  
    104.   
    105.   
    106.   
    107.         // Gets or sets output  
    108.   
    109.         public int Output  
    110.         {  
    111.   
    112.             get { return _output; }  
    113.   
    114.             set { _output = value; }  
    115.   
    116.         }  
    117.   
    118.     }  
    119.   
    120.   
    121.   
    122.     /// <summary>  
    123.   
    124.     /// The 'AbstractExpression' class  
    125.   
    126.     /// </summary>  
    127.   
    128.     abstract class Expression  
    129.     {  
    130.   
    131.         public void Interpret(Context context)  
    132.         {  
    133.   
    134.             if (context.Input.Length == 0)  
    135.   
    136.                 return;  
    137.   
    138.   
    139.   
    140.             if (context.Input.StartsWith(Nine()))  
    141.             {  
    142.   
    143.                 context.Output += (9 * Multiplier());  
    144.   
    145.                 context.Input = context.Input.Substring(2);  
    146.   
    147.             }  
    148.   
    149.             else if (context.Input.StartsWith(Four()))  
    150.             {  
    151.   
    152.                 context.Output += (4 * Multiplier());  
    153.   
    154.                 context.Input = context.Input.Substring(2);  
    155.   
    156.             }  
    157.   
    158.             else if (context.Input.StartsWith(Five()))  
    159.             {  
    160.   
    161.                 context.Output += (5 * Multiplier());  
    162.   
    163.                 context.Input = context.Input.Substring(1);  
    164.   
    165.             }  
    166.   
    167.   
    168.   
    169.             while (context.Input.StartsWith(One()))  
    170.             {  
    171.   
    172.                 context.Output += (1 * Multiplier());  
    173.   
    174.                 context.Input = context.Input.Substring(1);  
    175.   
    176.             }  
    177.   
    178.         }  
    179.   
    180.   
    181.   
    182.         public abstract string One();  
    183.   
    184.         public abstract string Four();  
    185.   
    186.         public abstract string Five();  
    187.   
    188.         public abstract string Nine();  
    189.   
    190.         public abstract int Multiplier();  
    191.   
    192.     }  
    193.   
    194.   
    195.   
    196.     /// <summary>  
    197.   
    198.     /// A 'TerminalExpression' class  
    199.   
    200.     /// <remarks>  
    201.   
    202.     /// Thousand checks for the Roman Numeral M   
    203.   
    204.     /// </remarks>  
    205.   
    206.     /// </summary>  
    207.   
    208.     class ThousandExpression : Expression  
    209.     {  
    210.   
    211.         public override string One() { return "M"; }  
    212.   
    213.         public override string Four() { return " "; }  
    214.   
    215.         public override string Five() { return " "; }  
    216.   
    217.         public override string Nine() { return " "; }  
    218.   
    219.         public override int Multiplier() { return 1000; }  
    220.   
    221.     }  
    222.   
    223.   
    224.   
    225.     /// <summary>  
    226.   
    227.     /// A 'TerminalExpression' class  
    228.   
    229.     /// <remarks>  
    230.   
    231.     /// Hundred checks C, CD, D or CM  
    232.   
    233.     /// </remarks>  
    234.   
    235.     /// </summary>  
    236.   
    237.     class HundredExpression : Expression  
    238.     {  
    239.   
    240.         public override string One() { return "C"; }  
    241.   
    242.         public override string Four() { return "CD"; }  
    243.   
    244.         public override string Five() { return "D"; }  
    245.   
    246.         public override string Nine() { return "CM"; }  
    247.   
    248.         public override int Multiplier() { return 100; }  
    249.   
    250.     }  
    251.   
    252.   
    253.   
    254.     /// <summary>  
    255.   
    256.     /// A 'TerminalExpression' class  
    257.   
    258.     /// <remarks>  
    259.   
    260.     /// Ten checks for X, XL, L and XC  
    261.   
    262.     /// </remarks>  
    263.   
    264.     /// </summary>  
    265.   
    266.     class TenExpression : Expression  
    267.     {  
    268.   
    269.         public override string One() { return "X"; }  
    270.   
    271.         public override string Four() { return "XL"; }  
    272.   
    273.         public override string Five() { return "L"; }  
    274.   
    275.         public override string Nine() { return "XC"; }  
    276.   
    277.         public override int Multiplier() { return 10; }  
    278.   
    279.     }  
    280.   
    281.   
    282.   
    283.     /// <summary>  
    284.   
    285.     /// A 'TerminalExpression' class  
    286.   
    287.     /// <remarks>  
    288.   
    289.     /// One checks for I, II, III, IV, V, VI, VI, VII, VIII, IX  
    290.   
    291.     /// </remarks>  
    292.   
    293.     /// </summary>  
    294.   
    295.     class OneExpression : Expression  
    296.     {  
    297.   
    298.         public override string One() { return "I"; }  
    299.   
    300.         public override string Four() { return "IV"; }  
    301.   
    302.         public override string Five() { return "V"; }  
    303.   
    304.         public override string Nine() { return "IX"; }  
    305.   
    306.         public override int Multiplier() { return 1; }  
    307.   
    308.     }  
    309. }  


    乐在其中设计模式(C#) - 解释器模式(Interpreter Pattern)

    乐在其中设计模式(C#) - 解释器模式(Interpreter Pattern)


    作者:webabcd


    介绍
    给定一个语言, 定义它的文法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言中的句子。


    示例
    有一个Message实体类,某个类对它的操作有Get()方法。现在要求用具有某一规则的中文语法来执行这个操作。



    MessageModel
    using  System;
    using  System.Collections.Generic;
    using  System.Text;

    namespace  Pattern.Interpreter
    {
        
    /// <summary>
        
    /// Message实体类
        
    /// </summary>

        public class MessageModel
        
    {
            
    /// <summary>
            
    /// 构造函数
            
    /// </summary>
            
    /// <param name="msg">Message内容</param>
            
    /// <param name="pt">Message发布时间</param>

            public MessageModel(string msg, DateTime pt)
            
    {
                
    this._message = msg;
                
    this._publishTime = pt;
            }


            
    private string _message;
            
    /// <summary>
            
    /// Message内容
            
    /// </summary>

            public string Message
            
    {
                
    get return _message; }
                
    set { _message = value; }
            }


            
    private DateTime _publishTime;
            
    /// <summary>
            
    /// Message发布时间
            
    /// </summary>

            public DateTime PublishTime
            
    {
                
    get return _publishTime; }
                
    set { _publishTime = value; }
            }

        }

    }


    SqlMessage
    using  System;
    using  System.Collections.Generic;
    using  System.Text;

    namespace  Pattern.Interpreter
    {
        
    /// <summary>
        
    /// Sql方式操作Message
        
    /// </summary>

        public class SqlMessage
        
    {
            
    /// <summary>
            
    /// 获取Message
            
    /// </summary>
            
    /// <returns></returns>

            public static List<MessageModel> Get()
            
    {
                List
    <MessageModel> l = new List<MessageModel>();
                l.Add(
    new MessageModel("SQL方式获取Message", DateTime.Now));

                
    return l;
            }

        }

    }


    Context
    using  System;
    using  System.Collections.Generic;
    using  System.Text;

    namespace  Pattern.Interpreter
    {
        
    /// <summary>
        
    /// Context
        
    /// </summary>

        public class Context
        
    {
            
    private string _input;
            
    private string _output;

            
    /// <summary>
            
    /// 构造函数
            
    /// </summary>
            
    /// <param name="input">输入内容</param>

            public Context(string input)
            
    {
                
    this._input = input;
            }


            
    /// <summary>
            
    /// 输入内容
            
    /// </summary>

            public string Input
            
    {
                
    get return _input; }
                
    set { _input = value; }
            }


            
    /// <summary>
            
    /// 输出内容
            
    /// </summary>

            public string Output
            
    {
                
    get return _output; }
                
    set { _output = value; }
            }

        }

    }


    AbstractExpression
    using  System;
    using  System.Collections.Generic;
    using  System.Text;

    namespace  Pattern.Interpreter
    {
        
    /// <summary>
        
    /// 抽象公式(AbstractExpression)
        
    /// </summary>

        public abstract class AbstractExpression
        
    {
            
    /// <summary>
            
    /// 解释Context的方法
            
    /// </summary>
            
    /// <param name="context">context</param>

            public void Interpret(Context context)
            
    {
                
    if (String.IsNullOrEmpty(context.Input))
                
    {
                    
    return;
                }


                context.Output 
    += GetCSharp(context.Input);
            }


            
    /// <summary>
            
    /// 获得输入内容所对应的C#代码
            
    /// </summary>
            
    /// <param name="source">source</param>
            
    /// <returns></returns>

            private string GetCSharp(string source)
            
    {
                
    string csharp = "";
                
    string word = "";

                
    // 从输入内容中取得要解释的词
                word = GetWord(source);

                
    // 从字典中找到word所对应的C#代码
                GetDictionary().TryGetValue(word, out csharp);

                
    return csharp;
            }


            
    /// <summary>
            
    /// 从输入内容中取得要解释的词
            
    /// </summary>
            
    /// <param name="source">source</param>
            
    /// <returns></returns>

            public abstract string GetWord(string source);

            
    /// <summary>
            
    /// 获取字典
            
    /// </summary>
            
    /// <returns></returns>

            public abstract Dictionary<stringstring> GetDictionary();
        }

    }


    DatabaseExpression
    using  System;
    using  System.Collections.Generic;
    using  System.Text;

    using  System.Text.RegularExpressions;

    namespace  Pattern.Interpreter
    {
        
    /// <summary>
        
    /// 终端公式(TerminalExpression)分析与数据库相关的
        
    /// </summary>

        public class DatabaseExpression : AbstractExpression
        
    {
            
    /// <summary>
            
    /// 从输入内容中取得要解释的词
            
    /// </summary>
            
    /// <param name="source">source</param>
            
    /// <returns></returns>

            public override string GetWord(string source)
            
    {
                MatchCollection mc;
                Regex r 
    = new Regex(@"\{(.*)\}");
                mc 
    = r.Matches(source);

                
    return mc[0].Groups[1].Value;
            }


            
    /// <summary>
            
    /// 获取与数据库相关的字典
            
    /// </summary>
            
    /// <returns></returns>

            public override Dictionary<stringstring> GetDictionary()
            
    {
                Dictionary
    <stringstring> d = new Dictionary<stringstring>();

                d.Add(
    "数据库""Sql");

                
    return d;
            }

        }

    }


    ObjectExpression
    using  System;
    using  System.Collections.Generic;
    using  System.Text;

    using  System.Text.RegularExpressions;

    namespace  Pattern.Interpreter
    {
        
    /// <summary>
        
    /// 终端公式(TerminalExpression)分析与对象相关的
        
    /// </summary>

        public class ObjectExpression : AbstractExpression
        
    {
            
    /// <summary>
            
    /// 从输入内容中取得要解释的词
            
    /// </summary>
            
    /// <param name="source">source</param>
            
    /// <returns></returns>

            public override string GetWord(string source)
            
    {
                MatchCollection mc;
                Regex r 
    = new Regex(@"\[(.*)\]");
                mc 
    = r.Matches(source);

                
    return mc[0].Groups[1].Value;
            }


            
    /// <summary>
            
    /// 获取与对象相关的字典
            
    /// </summary>
            
    /// <returns></returns>

            public override Dictionary<stringstring> GetDictionary()
            
    {
                Dictionary
    <stringstring> d = new Dictionary<stringstring>();

                d.Add(
    "信息""Message");

                
    return d;
            }

        }

    }


    MethodExpression
    using  System;
    using  System.Collections.Generic;
    using  System.Text;

    using  System.Text.RegularExpressions;

    namespace  Pattern.Interpreter
    {
        
    /// <summary>
        
    /// 终端公式(TerminalExpression)分析与方法相关的
        
    /// </summary>

        public class MethodExpression : AbstractExpression
        
    {
            
    /// <summary>
            
    /// 从输入内容中取得要解释的词
            
    /// </summary>
            
    /// <param name="source">source</param>
            
    /// <returns></returns>

            public override string GetWord(string source)
            
    {
                MatchCollection mc;
                Regex r 
    = new Regex(@"\((.*)\)");
                mc 
    = r.Matches(source);

                
    return mc[0].Groups[1].Value;
            }


            
    /// <summary>
            
    /// 获取与方法相关的字典
            
    /// </summary>
            
    /// <returns></returns>

            public override Dictionary<stringstring> GetDictionary()
            
    {
                Dictionary
    <stringstring> d = new Dictionary<stringstring>();

                d.Add(
    "获取"".Get()");

                
    return d;
            }

        }

    }



    client
    using  System;
    using  System.Data;
    using  System.Configuration;
    using  System.Collections;
    using  System.Web;
    using  System.Web.Security;
    using  System.Web.UI;
    using  System.Web.UI.WebControls;
    using  System.Web.UI.WebControls.WebParts;
    using  System.Web.UI.HtmlControls;

    using  Microsoft.CSharp;
    using  System.Reflection;
    using  System.Text;
    using  System.Collections.Generic;

    using  Pattern.Interpreter;

    public  partial  class  Interpreter : System.Web.UI.Page
    {
        
    protected void Page_Load(object sender, EventArgs e)
        
    {
            
    string chinese = "{数据库}[信息](获取)";
            Context context 
    = new Context(chinese);

            List
    <AbstractExpression> l = new List<AbstractExpression>();
            l.Add(
    new DatabaseExpression());
            l.Add(
    new ObjectExpression());
            l.Add(
    new MethodExpression());

            
    foreach (AbstractExpression exp in l)
            
    {
                exp.Interpret(context);
            }


            Assembly assembly 
    = Assembly.Load("Pattern.Interpreter");
            MethodInfo method 
    = assembly.GetType("Pattern.Interpreter." + context.Output.Split('.')[0]).GetMethod(context.Output.Split('.')[1].Replace("()"""));
            
    object obj = method.Invoke(nullnull);

            List
    <MessageModel> m = (List<MessageModel>)obj;

            Response.Write(
    "中文语法:" + chinese);
            Response.Write(
    "<br />");
            Response.Write(
    "解释后的C#代码:" + context.Output);
            Response.Write(
    "<br />");
            Response.Write(
    "执行结果:" + m[0].Message + " " + m[0].PublishTime.ToString());
        }

    }


    运行结果
    中文语法:{数据库}[信息](获取)
    解释后的C#代码:SqlMessage.Get()
    执行结果:SQL方式获取Message 2007-5-1 8:48:07


    参考
    http://www.dofactory.com/Patterns/PatternInterpreter.aspx


    OK
    [源码下载]

示例代码:

using System;
using System.Collections.Generic;
using System.Text;

namespace InterpreterPattern
{
    /// <summary>
    /// 上下文(环境)角色类:包含解释器之外的一些全局信息。
    /// </summary>
    public class Context
    {
        /// <summary>
        /// 变量对象集合
        /// </summary>
        private IDictionary<CharExpression, int> charExpressions = new Dictionary<CharExpression, int>();

        private string _input;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="input">输入内容</param>
        public Context(string input)
        {
            this._input = input;
        }

        /// <summary>
        /// 输入内容
        /// </summary>
        public string Input
        {
            get { return _input; }
            set { _input = value; }
        }

        /// <summary>
        /// 设置变量的值
        /// </summary>
        /// <param name="charExpression">变量</param>
        /// <param name="number">值</param>
        public void SetValue(CharExpression charExpression, int number)
        {
            if (!charExpressions.ContainsKey(charExpression))
            {
                charExpressions.Add(charExpression, number);
            }
            else
            {
                charExpressions[charExpression] = number;
            }
        }

        /// <summary>
        /// 获得变量的值
        /// </summary>
        /// <param name="charExpression">变量</param>
        /// <returns>值</returns>
        public int GetValue(CharExpression charExpression)
        {
            int number = 0;
            if (charExpressions.ContainsKey(charExpression))
            {
                number = charExpressions[charExpression];
            }
            return number;
        }
    }


    /// <summary>
    /// 抽象表达式类:声明一个抽象的解释操作,抽象语法树中所有的节点共享该抽象类。
    /// </summary>
    public abstract class AbstractExpression
    {
        /// <summary>
        /// 解释操作,完成具体的语法分析
        /// </summary>
        /// <param name="context">上下文</param>
        /// <returns>结果</returns>
        public abstract int Interpret(Context context);
    }


    /// <summary>
    /// 终结符表达式(TerminalExpression)角色类一:实现与文法中的终结符相关联的解释操作,一个句子中的每个终结符需要该类的一个实例 。
    /// 该类处理数字。
    /// </summary>
    public class NumnerExpression : AbstractExpression
    {
        private int number;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="number">数字</param>
        public NumnerExpression(int number)
        {
            this.number = number;
        }

        /// <summary>
        /// 解释操作,完成具体的语法分析
        /// </summary>
        /// <param name="context">上下文</param>
        /// <returns>结果</returns>
        public override int Interpret(Context context)
        {
            return number;
        }
    }

    /// <summary>
    /// 终结符表达式(TerminalExpression)角色类二:实现与文法中的终结符相关联的解释操作,一个句子中的每个终结符需要该类的一个实例 。
    /// 该类处理字符。
    /// </summary>
    public class CharExpression : AbstractExpression
    {
        /// <summary>
        /// 解释操作,完成具体的语法分析
        /// </summary>
        /// <param name="context">上下文</param>
        /// <returns>结果</returns>
        public override int Interpret(Context context)
        {
            return context.GetValue(this);
        }
    }

 
    /// <summary>
    /// 非终结符表达式(NonterminalExpression)角色类一:文法中的每条规则R::=R1R2…Rn都需要一个非终结符表带式角色,对于从R1到Rn的每个符号都维护一个抽象表达式角色的实例变量
    /// 解释一般要递归地调用表示从R1到Rn的那些对象的解释操作
    /// 该类处理加号。
    /// </summary>
    public class AddExpression : AbstractExpression
    {
        private AbstractExpression _left;
        private AbstractExpression _right;

        public AddExpression(AbstractExpression left, AbstractExpression right)
        {
            this._left = left;
            this._right = right;
        }

        /// <summary>
        /// 左部分
        /// </summary>
        public AbstractExpression Left
        {
            get { return _left; }
            set { _left = value; }
        }

        /// <summary>
        /// 右部分
        /// </summary>
        public AbstractExpression Right
        {
            get { return _right; }
            set { _right = value; }
        }

        /// <summary>
        /// 解释操作,完成具体的语法分析
        /// </summary>
        /// <param name="context">上下文</param>
        /// <returns>结果</returns>
        public override int Interpret(Context context)
        {
            return _left.Interpret(context) + _right.Interpret(context);
        }
    }

    /// <summary>
    /// 非终结符表达式(NonterminalExpression)角色类二:文法中的每条规则R::=R1R2…Rn都需要一个非终结符表带式角色,对于从R1到Rn的每个符号都维护一个抽象表达式角色的实例变量
    /// 解释一般要递归地调用表示从R1到Rn的那些对象的解释操作
    /// 该类处理减号。
    /// </summary>
    public class SubtractExpression : AbstractExpression
    {
        private AbstractExpression _left;
        private AbstractExpression _right;

        public SubtractExpression(AbstractExpression left, AbstractExpression right)
        {
            this._left = left;
            this._right = right;
        }

        /// <summary>
        /// 左部分
        /// </summary>
        public AbstractExpression Left
        {
            get { return _left; }
            set { _left = value; }
        }

        /// <summary>
        /// 右部分
        /// </summary>
        public AbstractExpression Right
        {
            get { return _right; }
            set { _right = value; }
        }

        /// <summary>
        /// 解释操作,完成具体的语法分析
        /// </summary>
        /// <param name="context">上下文</param>
        /// <returns>结果</returns>
        public override int Interpret(Context context)
        {
            return _left.Interpret(context) - _right.Interpret(context);
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            string input = "a-(b+2)";

            Context context = new Context(input);
            NumnerExpression num = new NumnerExpression(2);
            CharExpression a = new CharExpression();
            CharExpression b = new CharExpression();
            //赋值
            context.SetValue(a, 5);
            context.SetValue(b, 1);
            AbstractExpression expression = new SubtractExpression(a, new AddExpression(b, num));

            Console.WriteLine("结果:{0}", expression.Interpret(context));
            Console.ReadLine();
        }
    }
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值