儲存解釋過程中的輸入與輸出狀態:
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; }
}
}
}
定義解釋介面與共享解析邏輯:
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();
}
}
Input 原始語法字串,Output 累積解釋結果。| 模式角色 | 本例類別 | 說明 |
|---|---|---|
| AbstractExpression | AbstractExpression | 抽象運算式,模板方法 Interpret |
| TerminalExpression | DatabaseExpression, ObjectExpression, MethodExpression | 終端運算式,解析具體語法元素 |
| Context | Context | 上下文,儲存輸入輸出狀態 |
| Client | 測試頁面 | 組合運算式並啟動解釋 |