文法树抽象
public string Expression
{
get
{
return _Expression;
}
}
public abstract string Transfer();
}
文法树实例A
public class FruitInterpretor : Interpretor
{
public FruitInterpretor(string expression):base(expression)
{ }
public override string Transfer()
{
string result;
switch (Expression)
{
case "fo":
result = "橘子";
break;
case "fa":
result = "苹果";
break;
case "fb":
result = "香蕉";
break;
default:
result = "未知的水果";
break;
}
return result;
}
}
解释内容
public string InputContext
{
get
{
return _InputContext;
}
}
public string OutputContext
{
get
{
return _OutputContext;
}
set {
_OutputContext = value;
}
}
}
调用代码
namespace InterpretePattern
{
class Program
{
static void Main(string[] args)
{
//使用堆栈来做
int offset=0;
Stack<string> words=new Stack<string>();
InterpreteContext context = new InterpreteContext("i like fo fb and fa ");
FruitInterpretor interpetor;
for (int i = 0; i < context.InputContext.Length; i++)
{
switch (context.InputContext[i])
{
case ' ':
words.Push(context.InputContext.Substring(offset,i-offset));
offset=i+1;
break;
default:
break;
}
}
foreach (string express in words)
{
if (express.Length == 2 && express.StartsWith("f"))
{
interpetor = new FruitInterpretor(express);
context.OutputContext = interpetor.Transfer() + " " + context.OutputContext;
}
else
context.OutputContext = express + " " + context.OutputContext;
}
//string result = words.ToString();
Console.WriteLine(context.OutputContext);
Console.ReadKey();
}
}
}
执行结果:
i like 橘子 香蕉 and 苹果