该模式不属于GOF的23个设计模式,违背了开放封闭原则(对扩展开放,对修改关闭)
简单的计算器
类图
制图工具:draw.io
SimpleFactoryPattern.drawio.xml
C#代码
public abstract class Arithmetic
{
public double NumberA;
public double NumberB;
public abstract double GetResult();
}
public class SimpleFactory
{
public static Arithmetic CreateOperate(string operate)
{
Arithmetic arithmetic=null;
switch (operate)
{
case "+":
arithmetic = new Add();
break;
case "-":
arithmetic = new Subtract();
break;
case "*":
arithmetic = new Multiply();
break;
case "/":
arithmetic = new Divide();
break;
default:
break;
}
return arithmetic;
}
}
public class Add : Arithmetic
{
public override double GetResult()
{
return NumberA + NumberB;
}
}
public class Subtract : Arithmetic
{
public override double GetResult()
{
return NumberA - NumberB;
}
}
public class Multiply : Arithmetic
{
public override double GetResult()
{
return NumberA * NumberB;
}
}
public class Divide : Arithmetic
{
public override double GetResult()
{
if (NumberB==0)
{
throw new Exception("除数不能为0");
}
return NumberA / NumberB;
}
}
使用
Arithmetic arithmetic = SimpleFactory.CreateOperate("-");
arithmetic.NumberA = 10;
arithmetic.NumberB = 20;
double result=arithmetic.GetResult();
Console.WriteLine(result);