题目:以面向对象编程方式实现以下功能,输入两个数和操作符,进行“+”,“-”,“*”,"/"运行,显示结果
Operation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DesignPatterns
{
/// <summary>
/// 运算类
/// </summary>
public class Operation
{
protected string Sign = "";
private double fNumberA = 0, fNumberB = 0;
public double NumberA
{
get { return fNumberA;}
set { fNumberA = value; }
}
public double NumberB
{
get { return fNumberB; }
set { fNumberB = value; }
}
public virtual double Result
{
get { return 0; }
}
public string ToString()
{
return Convert.ToString(NumberA) + Sign +
Convert.ToString(NumberB) + "=" + Convert.ToString(Result);
}
}
/// <summary>
/// 加法运算类
/// </summary>
class OperationAdd : Operation
{
public OperationAdd()
{
Sign = "+";
}
public override double Result
{
get { return (NumberA + NumberB); }
}
}
/// <summary>
/// 减法运算类
/// </summary>
class OperationSub : Operation
{
public OperationSub()
{
Sign = "-";
}
public override double Result
{
get { return (NumberA - NumberB); }
}
}
/// <summary>
/// 乘法运算类
/// </summary>
class OperationMul : Operation
{
public OperationMul()
{
Sign = "*";
}
public override double Result
{
get { return NumberA * NumberB; }
}
}
/// <summary>
/// 除法运算类
/// </summary>
class OperationDiv : Operation
{
public OperationDiv()
{
Sign = "/";
}
public override double Result
{
get
{
if(NumberB==0) {
throw new Exception("被除数为零");
}
return (NumberA / NumberB);
}
}
}
/// <summary>
/// 简单工厂类
/// </summary>
public class OperationFactory
{
/// <summary>
/// 根据运算符取对应的运算类
/// </summary>
/// <param name="strOperation">运算符</param>
/// <returns>运算类</returns>
public static Operation GetOperation(string strOperation)
{
Operation fOperation = null;
switch (strOperation)
{
case "+":
fOperation = new OperationAdd();
break;
case "-":
fOperation = new OperationSub();
break;
case "*":
fOperation = new OperationMul();
break;
case "/":
fOperation = new OperationDiv();
break;
}
return fOperation;
}
}
}
客户端代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DesignPatterns
{
class Program
{
static void Main(string[] args)
{
Operation op = OperationFactory.GetOperation("*");
op.NumberA = 123.22;
op.NumberB = 111;
Console.Out.WriteLine(op.ToString());
Console.In.Read();
}
}
}
UML图
总结:
简单工厂模式就是利用面向对象的多态性,工厂类通过输入条件返回特定的实现类。