解析大括號語法,映射資料庫類型:
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace Pattern.Interpreter
{
///
/// 終端運算式(TerminalExpression)分析與資料庫相關的
///
public class DatabaseExpression : AbstractExpression
{
///
/// 從輸入內容中取得要解釋的詞
///
/// source
/// 解析出的詞
public override string GetWord(string source)
{
MatchCollection mc;
Regex r = new Regex(@"\{(.*)\}");
mc = r.Matches(source);
return mc[0].Groups[1].Value;
}
///
/// 獲取與資料庫相關的字典
///
/// 中文詞彙到 C# 代碼映射
public override Dictionary<string, string> GetDictionary()
{
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("數據庫", "Sql");
return d;
}
}
}
解析中括號語法,映射物件名稱:
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace Pattern.Interpreter
{
///
/// 終端運算式(TerminalExpression)分析與物件相關的
///
public class ObjectExpression : AbstractExpression
{
///
/// 從輸入內容中取得要解釋的詞
///
/// source
/// 解析出的詞
public override string GetWord(string source)
{
MatchCollection mc;
Regex r = new Regex(@"\[(.*)\]");
mc = r.Matches(source);
return mc[0].Groups[1].Value;
}
///
/// 獲取與物件相關的字典
///
/// 中文詞彙到 C# 代碼映射
public override Dictionary<string, string> GetDictionary()
{
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("信息", "Message");
return d;
}
}
}
| 運算式 | 語法符號 | 正則模式 | 解析目標 | 字典映射 |
|---|---|---|---|---|
| DatabaseExpression | { } | \{(.*)\} | 數據庫類型 | 數據庫 → Sql |
| ObjectExpression | [ ] | \[(.*)\] | 物件名稱 | 信息 → Message |
| MethodExpression | ( ) | \((.*)\) | 方法名稱 | 獲取 → .Get() |
此設計展示了解釋器模式如何將複雜語法分解為獨立運算式,各司其職再組合成完整解釋器。