解釋器模式:提供了評估語言的語法或表達式的方式,它屬於行爲型模式。這種模式實現了一個表達式接口,該接口解釋一個特定的上下文。
主要意圖:給定一個語言,定義它的文法表示,並定義一個解釋器,這個解釋器使用該標識來解釋語言中的句子。
主要解決:對於一些固定文法構建一個解釋句子的解釋器。
解決方案:構建語法樹,定義終結符與非終結符。
優點:
1、可擴展性比較好,靈活。
2、增加了新的解釋表達式的方式。
3、易於實現簡單文法。
缺點:
1、可利用場景比較少。
2、對於複雜的文法比較難維護。
3、解釋器模式會引起類膨脹。
4、解釋器模式採用遞歸調用方法。
解釋器類圖:
代碼實現:
客戶端代碼:
using System;
using System.Collections.Generic;
namespace _01解釋器模式_結構圖
{
class Program
{
static void Main(string[] args)
{
Context context = new Context();
IList<AbstractExpression> list = new List<AbstractExpression>();
list.Add(new TerminalExpression());
list.Add(new NonterminalExpression());
list.Add(new TerminalExpression());
list.Add(new TerminalExpression());
foreach (AbstractExpression exp in list)
{
exp.Interpret(context);
}
Console.Read();
}
}
}
抽象解釋器:
using System;
using System.Collections.Generic;
using System.Text;
namespace _01解釋器模式_結構圖
{
abstract class AbstractExpression
{
public abstract void Interpret(Context context);
}
}
終結符表達式:
using System;
using System.Collections.Generic;
using System.Text;
namespace _01解釋器模式_結構圖
{
class TerminalExpression:AbstractExpression
{
public override void Interpret(Context context)
{
Console.WriteLine("終端解釋器");
}
}
}
非終結符表達式:
using System;
using System.Collections.Generic;
using System.Text;
namespace _01解釋器模式_結構圖
{
class NonterminalExpression:AbstractExpression
{
public override void Interpret(Context context)
{
Console.WriteLine("非終端解釋器");
}
}
}
環境角色:
using System;
using System.Collections.Generic;
using System.Text;
namespace _01解釋器模式_結構圖
{
class Context
{
private string input;
public string Input
{
get { return input; }
set { input = value; }
}
private string output;
public string Output
{
get { return output; }
set { output = value; }
}
}
}