操作流程:
1. 新建Operation 类
2. 新建OperationAdd 类,并继承Operation 类
3. 新建OperationSub 类,并继承Operation 类
4. 新建OperationMul 类,并继承Operation 类
5. 新建OperationDiv 类,并继承Operation 类
6. 新建创造实例的工厂类OperationFactory
7. Main 方法操作根据传入的运算符创造相对应的操作类,并执行相对应的运算逻辑
1、新建Operation 类
public class Operation
{
public double numberA { get; set; }
public double numberB { get; set; }
public virtual double getResult()
{
return 0;
}
}
2. 新建OperationAdd 类,并继承Operation 类
public class OperationAdd : Operation
{
//实现操作加法运算
public override double getResult()
{
double result = 0;
result = numberA + numberB;
return result;
}
}
3. 新建OperationSub 类,并继承Operation 类
public class OperationSub : Operation
{
//实现减法操作
public override double getResult()
{
double result = 0;
result = numberA - numberB;
return result;
}
}
4. 新建OperationMul 类,并继承Operation 类
public class OperationMul : Operation
{
//实现乘法操作
public override double getResult()
{
double result = 0;
result = numberA * numberB;
return result;
}
}
5. 新建OperationDiv 类,并继承Operation 类
public class OperationDiv : Operation
{
//实现除法操作
public override double getResult()
{
double result = 0;
if (numberB == 0)
throw new Exception("除数不能为0");
result = numberA / numberB;
return result;
}
}
6. 新建创造实例的工厂类OperationFactory
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:
break;
}
return oper;
}
}
7. Main 方法操作根据传入的运算符创造相对应的操作类,并执行相对应的运算逻辑
class Program
{
static void Main(string[] args)
{
try
{
Operation oper = OperationFactory.CreateOperate("+");
oper.numberA = 3;
oper.numberB = 2;
double result = oper.getResult();
Console.WriteLine(result);
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
throw;
}
}
}
|
请发表评论