// 工厂生成对象类
public class OperationFactory
{
public static OperationClass GetOperation(string operationType)
{
OperationClass opera = null;
switch (operationType)
{
case "+":
opera = new AddOperation();
break;
case "-":
opera = new SubOperation();
break;
case "*":
opera = new MulOperation();
break;
case "/":
opera = new DivOperation();
break;
case "sqrt":
opera = new SqrtOperation();
break;
case "squa":
opera = new SquareOperation();
break;
default:
break;
}
return opera;
}
}
// 运算符基类
public abstract class OperationClass
{
public double NumA { get; set; }
public double NumB { get; set; }
public abstract double GetResult();
}
// 加号类
public class AddOperation : OperationClass
{
public override double GetResult()
{
return NumA + NumB;
}
}
// 减号类
public class SubOperation : OperationClass
{
public override double GetResult()
{
return NumA - NumB;
}
}
// 除号类
public class DivOperation : OperationClass
{
public override double GetResult()
{
try
{
if (NumB.Equals(0))
{
throw new DivideByZeroException("分母为零");
}
return NumA / NumB;
}
catch (DivideByZeroException ex)
{
Console.WriteLine(ex);
}
return 0;
}
}
// 乘号类
public class MulOperation : OperationClass
{
public override double GetResult()
{
return NumA * NumB;
}
}
// 开根号类
public class SqrtOperation : OperationClass
{
public override double GetResult()
{
return Math.Sqrt(NumA);
}
}
// 业务运用类
public class OperationOutput
{
public void Show()
{
OperationClass ope;
do
{
Console.WriteLine("请输入正确的运算符: * / + - sqrt squa");
ope = OperationFactory.GetOperation(Console.ReadLine());
}
while (ope == null);
Console.WriteLine("请输入第一个数字");
ope.NumA = double.Parse(Console.ReadLine());
if (!(ope is SqrtOperation))
{
Console.WriteLine("请输入第二个数字");
ope.NumB = double.Parse(Console.ReadLine());
}
Console.WriteLine("结果是:" + ope.GetResult());
Console.WriteLine();
}
}
1)缺点:每新增一种操作,就需要修改 OperationFactory 类的 GetOperation(string operationType) 方法,这违法了对扩展开放,对修改封闭的原则。
2)可通过工厂模式、抽象工厂的方式得到适当改善,可通过反射彻底改善。