原文:乐在其中设计模式(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<string, string> 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);



            ].Value;

        }



        /**//// <summary>

        /// 获取与数据库相关的字典

        /// </summary>

        /// <returns></returns>

        public override Dictionary<string, string> GetDictionary()

        {

            Dictionary<string, string> d = new Dictionary<string, string>();



            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);



            ].Value;

        }



        /**//// <summary>

        /// 获取与对象相关的字典

        /// </summary>

        /// <returns></returns>

        public override Dictionary<string, string> GetDictionary()

        {

            Dictionary<string, string> d = new Dictionary<string, string>();



            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);



            ].Value;

        }



        /**//// <summary>

        /// 获取与方法相关的字典

        /// </summary>

        /// <returns></returns>

        public override Dictionary<string, string> GetDictionary()

        {

            Dictionary<string, string> d = new Dictionary<string, string>();



            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 ].Replace("()", ""));

        object obj = method.Invoke(null, null);



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



        Response.Write("中文语法:" + chinese);

        Response.Write("<br />");

        Response.Write("解释后的C#代码:" + context.Output);

        Response.Write("<br />");

        Response.Write(].PublishTime.ToString());

    }

}

运行结果

中文语法:{数据库}[信息](获取)

解释后的C#代码:SqlMessage.Get()

执行结果:SQL方式获取Message 2007-5-1 8:48:07





参考

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





OK

[源码下载]

乐在其中设计模式(C#) - 解释器模式(Interpreter Pattern)的更多相关文章

  1. C#设计模式:解释器模式(Interpreter Pattern)

    一,C#设计模式:解释器模式(Interpreter Pattern) 1,解释器模式的应用场合是Interpreter模式应用中的难点,只有满足“业务规则频繁变化,且类似的模式不断重复出现,并且容易 ...

  2. 二十四种设计模式:解释器模式(Interpreter Pattern)

    解释器模式(Interpreter Pattern) 介绍给定一个语言, 定义它的文法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言中的句子. 示例有一个Message实体类,某个类对它的 ...

  3. 乐在其中设计模式(C#) - 提供者模式(Provider Pattern)

    原文:乐在其中设计模式(C#) - 提供者模式(Provider Pattern) [索引页][源码下载] 乐在其中设计模式(C#) - 提供者模式(Provider Pattern) 作者:weba ...

  4. 乐在其中设计模式(C#) - 访问者模式(Visitor Pattern)

    原文:乐在其中设计模式(C#) - 访问者模式(Visitor Pattern) [索引页][源码下载] 乐在其中设计模式(C#) - 访问者模式(Visitor Pattern) 作者:webabc ...

  5. 乐在其中设计模式(C#) - 策略模式(Strategy Pattern)

    原文:乐在其中设计模式(C#) - 策略模式(Strategy Pattern) [索引页][源码下载] 乐在其中设计模式(C#) - 策略模式(Strategy Pattern) 作者:webabc ...

  6. 乐在其中设计模式(C#) - 状态模式(State Pattern)

    原文:乐在其中设计模式(C#) - 状态模式(State Pattern) [索引页][源码下载] 乐在其中设计模式(C#) - 状态模式(State Pattern) 作者:webabcd 介绍 允 ...

  7. 乐在其中设计模式(C#) - 备忘录模式(Memento Pattern)

    原文:乐在其中设计模式(C#) - 备忘录模式(Memento Pattern) [索引页][源码下载] 乐在其中设计模式(C#) - 备忘录模式(Memento Pattern) 作者:webabc ...

  8. 乐在其中设计模式(C#) - 迭代器模式(Iterator Pattern)

    原文:乐在其中设计模式(C#) - 迭代器模式(Iterator Pattern) [索引页][源码下载] 乐在其中设计模式(C#) - 迭代器模式(Iterator Pattern) 作者:weba ...

  9. 乐在其中设计模式(C#) - 命令模式(Command Pattern)

    原文:乐在其中设计模式(C#) - 命令模式(Command Pattern) [索引页][源码下载] 乐在其中设计模式(C#) - 命令模式(Command Pattern) 作者:webabcd ...

随机推荐

  1. 陈词滥调,正确使用memset

    前项目发现一个问题,计划永远是一个dynamic_cast当一个异常动态转换,搜索了半天才发现问题竟然是在memset使用,见.但当处于几十万行代码量级中时,就变得不太那么easy定位了. 本文归纳了 ...

  2. 从零開始制作H5应用(4)——V4.0,增加文字并给文字加特效

    之前,我们分三次完毕了我们第一个H5应用的三个迭代版本号: V1.0--简单页面滑动切换 V2.0--多页切换,透明过渡及交互指示 V3.0--加入loading,music及自己主动切换 这已经是一 ...

  3. VSTO 学习笔记(六)在 Excel 2010中使用RDLC报表

    原文:VSTO 学习笔记(六)在 Excel 2010中使用RDLC报表 Excel具有强大的图表显示.分析功能,这点毋庸置疑,但是如果将常规MIS系统中的数据以报表的形式在Excel中显示,却并不那 ...

  4. hdu2563(递推dp)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2563 解题思路:要分两种情况来考虑,a(n)为向上,b(n)为向左跟向右,f(n)为当前方案数.a(n ...

  5. LeetCode_Merge Two Sorted Lists

    一.题目 Merge Two Sorted Lists My Submissions Merge two sorted linked lists and return it as a new list ...

  6. TBDR缺点

    TBDR全称Tile-based Deferred Rendering.它是Power VR独特的TBR技术的一种延伸实现手段.TBR/TBDR通过将每一帧画面划分成多个矩形区域,并对区域内的全部像素 ...

  7. 【STL】关联容器 — hash_set

    容器hash_set是以hash table为底层机制的,差点儿所有的操作都是转调用hash table提供的接口.因为插入无法存储同样的键值,所以hash_set的插入操作所有都使用hash tab ...

  8. 在ireport中使用checkbox

    在网上搜索了很多实现checkbox的办法, 主要是利用打钩图片实现. 下面是我的做法,也不怎么高明, 不过比利用图片好. 后台 map.put("lifeTimePartFlag" ...

  9. J2EE互联网产品打造

    CSDN的各位技术朋友们,你们好: 我司最近正在研发一套J2EE的互联网产品,前期功能设计例如以下: 1.权限管理 2.菜单管理 3.系统设置 4.页面管理[主要做静态化] 5.任务管理[数据同步以及 ...

  10. HttpApplication处理对象与HttpModule处理模块

    HttpApplication处理对象与HttpModule处理模块 (第三篇) 一.HttpApplication对象简述 在HttpRuntime创建了HttpContext对象之后,HttpRu ...