原文:乐在其中设计模式(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. POJ1505&amp;&amp;UVa714 Copying Books(DP)

    Copying Books Time Limit: 3000MS Memory Limit: 10000K Total Submissions: 7109 Accepted: 2221 Descrip ...

  2. UML简单介绍

    UML的全称是统一建模语言:Unified Modeling Language. 是用来为面向对象开发系统的产品进行说明可视化和编制文档的方法. 它是一种标准的图形化建模语言,是面向对象分析与设计的一 ...

  3. firefox同步数据时无响应问题

    之前设置了firefox的数据同步,可以在不同电脑上,同步自己的书签等信息,感觉很方便实用,最近在点工具立即同步时,不报错,书签也没有同步,没有任何响应: 后来查了许多网上资料,都不见效,无意间看到 ...

  4. PV(访问量)、UV(独立访客)、IP(独立IP) (转)

    网站统计中的PV(访问量):UV(独立访客):IP(独立IP)的定义与区别今天使用了雅虎统计,看到里面就有这个,就说说,其实里面的uv大家可能觉得很新奇,但是和站长统计里的独立访客是一样的嘛.---- ...

  5. TCP关闭过程

    状态迁移 . SO_LINGER/ SO_REUSEADDR TCP正常的关闭过程如下(四次握手过程): (FIN_WAIT_1) A ---FIN---> B(CLOSE_WAIT) (FIN ...

  6. ural1018(树形dp)

    题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=17662 题意:给一棵边有权值的二叉树,节点编号为1-n,1是根节点 ...

  7. URAL 1297 后缀数组:求最长回文子串

    思路:这题下午搞了然后一直WA,后面就看了Discuss,里面有个数组:ABCDEFDCBA,这个我输出ABCD,所以错了. 然后才知道自己写的后缀数组对这个回文子串有bug,然后就不知道怎么改了. ...

  8. 设计模式学习一:strategyPattern

    #ifndef STRATEGYPATTERN_H_#define STRATEGYPATTERN_H_#include<iostream>using namespace std; //策 ...

  9. 关于SVN配置文件的一个小例子

    1   背景假设 厦门央瞬公司是一家电子元器件设备供应商,其中有个ARM部门,专门负责ARM芯片的方案设计.销售,并在北京.上海各设立了一个办事处.对于工作日志,原先采用邮件方式发给经理,但是这种方式 ...

  10. 去掉word中向下的箭头^l----->^p

    去掉word中向下的箭头 在网页上复制文章到word中,会发现有很多向下的箭头,这些 符号叫做软回车符.如何去掉这些向下的箭头呢.步骤如下: 方法/步骤 按Ctrl+H,弹出全局替换窗口,输入查找内容 ...