using System;
namespace Ahoo.Demo.DesignPatterns.Patterns.SimpleFactory
{
/// <summary>
/// 简单工厂类
/// </summary>
public class OperationFactory
{
public static Operation CreateOperation(string oper, double FirstNumber = 0, double SecondNumber = 0)
{
Operation _Operation;
switch (oper)
{
case "+":
_Operation = new AddOperation
{
FirstNumber = FirstNumber,
SecondNumber = SecondNumber
};
break;
case "-":
_Operation = new SubOperation
{
FirstNumber = FirstNumber,
SecondNumber = SecondNumber
};
break;
case "*":
_Operation = new MulOperation
{
FirstNumber = FirstNumber,
SecondNumber = SecondNumber
};
break;
case "/":
_Operation = new DivOperation
{
FirstNumber = FirstNumber,
SecondNumber = SecondNumber
};
break;
default:
throw new ArgumentException("操作符有误!");
}
return _Operation;
}
}
/// <summary>
/// 抽象类
/// </summary>
public abstract class Operation
{
public double FirstNumber { get; set; }
public double SecondNumber { get; set; }
public abstract double GetResult();
}
/// <summary>
/// 具体操作子类(+)
/// </summary>
public class AddOperation : Operation
{
public override double GetResult()
{
double result = FirstNumber + SecondNumber;
return result;
}
}
/// <summary>
/// 具体操作子类(-)
/// </summary>
public class SubOperation : Operation
{
public override double GetResult()
{
double result = FirstNumber - SecondNumber;
return result;
}
}
/// <summary>
/// 具体操作子类(*)
/// </summary>
public class MulOperation : Operation
{
public override double GetResult()
{
double result = FirstNumber * SecondNumber;
return result;
}
}
/// <summary>
/// 具体操作子类(/)
/// </summary>
public class DivOperation : Operation
{
public override double GetResult()
{
if (SecondNumber == 0)
{
throw new ArgumentException("参数[SecondNumber]不能为0!");
}
double result = FirstNumber / SecondNumber;
return result;
}
}
public class Client
{
public static void Execute()
{
Console.WriteLine("********请输入操作符********");
string str_oper = Console.ReadLine();
Operation operation = OperationFactory.CreateOperation(str_oper);
Console.WriteLine("请输入操作符 第一个操作数");
operation.FirstNumber = Double.Parse(Console.ReadLine());
Console.WriteLine("请输入操作符 第二个操作数");
operation.SecondNumber = Double.Parse(Console.ReadLine());
Console.WriteLine("结果为:{0}", operation.GetResult());
}
}
}
设计模式实例-简单工厂模式
最新推荐文章于 2024-08-24 08:08:52 发布