欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

简单工厂设计模式

程序员文章站 2022-06-25 19:02:10
//简单工厂,适合具体实现不同,例如根据配置文件实例化不同的数据库,不同的语言版本. #region 定义基类(属性和功能) public class Operation { private double numberA = 0; public double NumberA { get { retu ......

//简单工厂,适合具体实现不同,例如根据配置文件实例化不同的数据库,不同的语言版本.
#region 定义基类(属性和功能)
public class Operation
{
private double numberA = 0;
public double NumberA
{
get { return numberA; }
set { numberA = value; }
}

private double numberB = 0;
public double NumberB
{
get { return numberB; }
set { numberB = value; }
}

public virtual double GetResult()
{
return 0;
}
}
#endregion 定义基类(属性和功能)
#region 具体实现
public class OperatonAdd : Operation
{
public override double GetResult()
{
return NumberA + NumberB;
}
}

public class OperatonSub : Operation
{
public override double GetResult()
{
return NumberA - NumberB;
}
}
public class OperatonMul : Operation
{
public override double GetResult()
{
return NumberA * NumberB;
}
}

public class OperatonDiv: Operation
{
public override double GetResult()
{
if (NumberB == 0)
throw new Exception("除数不能为0");
return NumberA / NumberB;
}
}
#endregion
#region 工厂根据条件实例化
public class OperationFactory
{

public static Operation CreateOperaton(string operate)
{

Operation oper = null;
switch (operate)
{
case "+":
oper = new OperatonAdd();
break;
case "-":
oper = new OperatonSub();
break;
case "*":
oper = new OperatonMul();
break;
case "/":
oper = new OperatonDiv();
break;

}
return oper;
}
}

  #endregion 工厂根据条件实例化