简单工厂设计模式
//简单工厂,适合具体实现不同,例如根据配置文件实例化不同的数据库,不同的语言版本.
#region 定义基类(属性和功能)
public class Operation
{
private double numberA = 0;
public double NumberA
{
get { return numberA; }
set { numberA = value; }
}
private double numberB = 0;
public double NumberB
{
get { return numberB; }
set { numberB = value; }
}
public virtual double GetResult()
{
return 0;
}
}
#endregion 定义基类(属性和功能)
#region 具体实现
public class OperatonAdd : Operation
{
public override double GetResult()
{
return NumberA + NumberB;
}
}
public class OperatonSub : Operation
{
public override double GetResult()
{
return NumberA - NumberB;
}
}
public class OperatonMul : Operation
{
public override double GetResult()
{
return NumberA * NumberB;
}
}
public class OperatonDiv: Operation
{
public override double GetResult()
{
if (NumberB == 0)
throw new Exception("除数不能为0");
return NumberA / NumberB;
}
}
#endregion
#region 工厂根据条件实例化
public class OperationFactory
{
public static Operation CreateOperaton(string operate)
{
Operation oper = null;
switch (operate)
{
case "+":
oper = new OperatonAdd();
break;
case "-":
oper = new OperatonSub();
break;
case "*":
oper = new OperatonMul();
break;
case "/":
oper = new OperatonDiv();
break;
}
return oper;
}
}
#endregion 工厂根据条件实例化