解释器模式(Interpreter):给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
namespace InterpreterDesign { public abstract class AbstractExpression { public abstract void Interpret(Context context); } public class TerminalExpression : AbstractExpression { public override void Interpret(Context context) { Console.WriteLine("终端解释器"); } } public class NonterminalExpression:AbstractExpression { public override void Interpret(Context context) { Console.WriteLine("非终端解释器"); } } public 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; } } } }
测试代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
InterpreterDesign.Context context = new InterpreterDesign.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); }