//簡單工廠,適合具體實現不同,例如根據配置文件實例化不同的資料庫,不同的語言版本. #region 定義基類(屬性和功能) public class Operation { private double numberA = 0; public double NumberA { get { retu ...
//簡單工廠,適合具體實現不同,例如根據配置文件實例化不同的資料庫,不同的語言版本.
#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 工廠根據條件實例化