简单工厂模式
// 操作类
public class Operation
{
private double _numberA = 0;
private double _numberB = 0;
public double NumberA {
get { return _numberA; }
set { _numberA = value; }
}
public double NumberB {
get { return _numberB; }
set { _numberB = value; }
}
public virtual double GetResult()
{
double result = 0;
return result;
}
}
// 具体操作类:操作类
class OperationAdd : Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA + NumberB;
return result;
}
}
// 工厂类,用来控制创造操作实例
public class OperationFactory
{
public static Operation CreateOperate (string operate)
{
Operation oper = null;
switch (operate)
{
case "+":
oper = new OperationAdd();
break;
case "-":
oper = new OperationSub();
break;
case "*":
oper = new OperationMul();
break;
case "/":
oper = new OperationDiv();
break;
default:
throw new Exception("请输入正确的运算符!");
}
return oper;
}
}
Console.Write("请输入数字A:");
string strNumberA = Console.ReadLine();
Console.Write("请输入运算符(+、-、*、/):");
string strOperate = Console.ReadLine();
Console.Write("请输入数字B:");
string strNumberB = Console.ReadLine();
Operation oper = OperationFactory.CreateOperate(strOperate);
oper.NumberA = Convert.ToDouble(strNumberA);
oper.NumberB = Convert.ToDouble(strNumberB);
double result = oper.GetResult();
Console.WriteLine(oper.NumberA + strOperate + oper.NumberB + "=" + result);
Console.ReadLine();