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

C# 設計模式:解釋器模式上下文與抽象運算式 (3/5)

     編輯:關於C語言

上下文:Context

儲存解釋過程中的輸入與輸出狀態:

using System;
using System.Collections.Generic;
using System.Text;

namespace Pattern.Interpreter
{
    /// 
    /// Context
    /// 
    public class Context
    {
        private string _input;
        private string _output;

        /// 
        /// 建構函式
        /// 
        /// 輸入內容
        public Context(string input)
        {
            this._input = input;
        }

        /// 
        /// 輸入內容
        /// 
        public string Input
        {
            get { return _input; }
            set { _input = value; }
        }

        /// 
        /// 輸出內容
        /// 
        public string Output
        {
            get { return _output; }
            set { _output = value; }
        }
    }
}

抽象運算式:AbstractExpression

定義解釋介面與共享解析邏輯:

using System;
using System.Collections.Generic;
using System.Text;

namespace Pattern.Interpreter
{
    /// 
    /// 抽象運算式(AbstractExpression)
    /// 
    public abstract class AbstractExpression
    {
        /// 
        /// 解釋 Context 的方法
        /// 
        /// context
        public void Interpret(Context context)
        {
            if (String.IsNullOrEmpty(context.Input))
            {
                return;
            }

            context.Output += GetCSharp(context.Input);
        }

        /// 
        /// 獲得輸入內容所對應的 C# 代碼
        /// 
        /// source
        /// C# 代碼片段
        private string GetCSharp(string source)
        {
            string csharp = "";
            string word = "";

            // 從輸入內容中取得要解釋的詞
            word = GetWord(source);

            // 從字典中找到 Word 所對應的 C# 代碼
            GetDictionary().TryGetValue(word, out csharp);

            return csharp;
        }

        /// 
        /// 從輸入內容中取得要解釋的詞
        /// 
        /// source
        /// 解析出的詞
        public abstract string GetWord(string source);

        /// 
        /// 獲取字典
        /// 
        /// 映射字典
        public abstract Dictionary<string, string> GetDictionary();
    }
}

AbstractExpression 模板方法設計

  • Interpret():模板方法,定義解釋流程骨架(檢查輸入 → 解析詞彙 → 字典查找 → 累加輸出)。
  • GetCSharp():私有輔助方法,封裝「解析 → 映射」核心邏輯。
  • GetWord():抽象方法,由子類別實作特定語法解析(正則表達式)。
  • GetDictionary():抽象方法,由子類別提供領域詞彙映射表。

Context 角色職責

  • 全域狀態:Input 原始語法字串,Output 累積解釋結果。
  • 資料共享:所有運算式共享同一 Context 實例,實現協作解釋。
  • 狀態演進:每個運算式處理後更新 Output,供下一個運算式使用。

解釋器模式角色對應(前三篇)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
模式角色本例類別說明
AbstractExpressionAbstractExpression抽象運算式,模板方法 Interpret
TerminalExpressionDatabaseExpression, ObjectExpression, MethodExpression終端運算式,解析具體語法元素
ContextContext上下文,儲存輸入輸出狀態
Client測試頁面組合運算式並啟動解釋