C# 简单工厂模式
static void Main(string[] args)
{
Console.WriteLine("NumberA:");
string NumberA = Console.ReadLine();
Console.WriteLine("NumberB:");
string NumberB = Console.ReadLine();
Console.WriteLine("运算符:");
string Symbol = Console.ReadLine();
Operation oper;
oper = OperationFactory.createOperate(Symbol);
oper.NumberA = Convert.ToDouble(NumberA);
oper.NumberB = Convert.ToDouble(NumberB);
double result = oper.GetResult();
Console.WriteLine("结果:"+ result);
}
//Operation 类
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; ;
}
}
//OperationAdd类
class OperationAdd : Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA + NumberB;
return result;
}
}
//OperationSub类
class OperationSub : Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA - NumberB;
return result;
}
}
//OperationMul类
class OperationMul : Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA * NumberB;
return result;
}
}
//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;
}
return oper;
}
}