程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 設計模式(C#) - 解釋器模式(Interpreter Pattern)(5)

設計模式(C#) - 解釋器模式(Interpreter Pattern)(5)

編輯:關於C語言

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<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 = assembly.GetType("Pattern.Interpreter." + context.Output.Split('.')[0]).GetMethod(context.Output.Split('.')[1].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("執行結果:" + 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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved