23.解释器模式
class Program
{
static void Main(string[] args)
{
BooleanExp booleanExp1 = new BooleanExp("true");
BooleanExp booleanExp2 = new BooleanExp("false");
OrExp orExp = new OrExp(booleanExp1, booleanExp2);//或表达式
Console.WriteLine(orExp.Interpret());
AndExp andExp = new AndExp(booleanExp1, booleanExp2);//与表达式
Console.WriteLine(andExp.Interpret());
Console.Read();
}
}
abstract class ExpressionClass
{
public abstract bool Interpret();
}
class BooleanExp : ExpressionClass//布尔表达式
{
string Context;
public BooleanExp(string context)
{
Context = context;
}
public override bool Interpret()
{
return Context.ToLower() == "true";
}
}
class OrExp : ExpressionClass//或表达式
{
BooleanExp Exp1;
BooleanExp Exp2;
public OrExp(BooleanExp exp1, BooleanExp exp2)
{
Exp1 = exp1;
Exp2 = exp2;
}
public override bool Interpret()
{
return Exp1.Interpret() || Exp2.Interpret();
}
}
class AndExp : ExpressionClass// 与表达式
{
BooleanExp Exp1;
BooleanExp Exp2;
public AndExp(BooleanExp exp1, BooleanExp exp2)
{
Exp1 = exp1;
Exp2 = exp2;
}
public override bool Interpret()
{
return Exp1.Interpret() && Exp2.Interpret();
}
}