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

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

編輯:關於C#

返回“設計模式(C#)系列文章索引”

介紹

給定一個語言, 定義它的文法的一種表示,並定義一個解釋器,該解釋器使用該表示來解釋語言中的句子。

示例

有一個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);

      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("數據庫", "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<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);

      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