【算法】解释器模式解决字符串四则运算问题

public class MyInterpreter
{
//{"(","1","+","2",")","*","3.5"}
public MyInterpreter(string[] tokens)
{
this.Tokens = tokens;
this.Finger = 0;
}
/*
* E->E+T|E-T|T;
* T->T*F|T/F|F;
* F->(E)|id;
*/
public int Finger { get; set; }
public string[] Tokens { get; set; }
public double Exp()
{
double result = this.Term();
while (true)
{
if (Finger < Tokens.Length && Tokens[Finger] == "+")
{
Match("+");
result += Term();
}
else if (Finger < Tokens.Length && Tokens[Finger] == "-")
{
Match("-");
result -= Term();
}
else
{
break;
}
}

return result;
}

public double Term()
{
double result = this.Factor();

while (true)
{
if (Finger < Tokens.Length && Tokens[Finger] == "*")
{
Match("*");
result *= Factor();
}
else if (Finger < Tokens.Length && Tokens[Finger] == "/")
{
Match("/");
result /= Factor();
}
else
{
break;
}
}
return result;
}

public double Factor()
{
double result = 0;

if (Finger < Tokens.Length && Tokens[Finger] == "(")
{
Match("(");
result = this.Exp();
Match(")");
}
else if (Finger < Tokens.Length && IsDigtal(Tokens[Finger]))
{
result = double.Parse(Tokens[Finger]);
Finger++;
}
else
{
Console.WriteLine("{0}不是合法元素", Tokens[Finger]);
}

return result;
}

void Match(string expectedStr)
{
if (Tokens[Finger] == expectedStr)
Finger++;
else
{
Console.WriteLine("期待{0},而给定是{1}", expectedStr, Tokens[Finger]);