首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 設計模式:解釋器模式資料庫與物件終端運算式 (4/5)

     編輯:關於C語言

終端運算式:DatabaseExpression

解析大括號語法,映射資料庫類型:

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

終端運算式:ObjectExpression

解析中括號語法,映射物件名稱:

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

設計特點

  • 正則表達式解析:各運算式專注特定符號對(大括號/中括號/括號)。
  • 字典映射:領域詞彙到技術實現的解耦映射,易於維護擴展。
  • 單一職責:每個運算式類別只處理一類語法元素。
  • 可組合性:客戶端按序組合多個運算式完成完整解釋。

此設計展示了解釋器模式如何將複雜語法分解為獨立運算式,各司其職再組合成完整解釋器。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved