2.Abstract Factory 抽象工厂(创建型模式)之简单工厂

时间:2024-01-07 20:11:38

简单工厂

1.只有一个工厂(具体的,没有抽象)

2.只生产一种产品(抽象的产品)

3.这种产品可以有多种具体产品类型(派生)

2.Abstract Factory 抽象工厂(创建型模式)之简单工厂

代码实现

class Program
{
static void Main(string[] args)
{
int number1 = ;
int number2 = ;
Compute compute = SimpleFactory.GetComputer("+");
compute.Number1 = number1;
compute.Number2 = number2;
Console.WriteLine(compute.GetResult()); Console.ReadKey();
}
} /// <summary>
/// 简单工厂
/// </summary>
public static class SimpleFactory
{ public static Compute GetComputer(string operate)
{
Compute computer = null;
switch (operate)
{
case "+":
computer = new AddCompute();
break;
case "-":
computer = new SubCompute();
break;
case "*":
computer = new ChengFaCompute();
break;
case "/":
computer = new ChuFaCompute();
break;
default:
break;
}
return computer;
}
} /// <summary>
/// 计算类
/// </summary>
public abstract class Compute
{
protected int number1; public int Number1
{
get { return number1; }
set { number1 = value; }
}
protected int number2; public int Number2
{
get { return number2; }
set { number2 = value; }
} public abstract int GetResult(); } /// <summary>
/// 加法
/// </summary>
public class AddCompute : Compute
{
public override int GetResult()
{
return number1 + number2;
}
}
/// <summary>
/// 减法
/// </summary>
public class SubCompute : Compute
{
public override int GetResult()
{
return number1 - number2;
}
}
/// <summary>
/// 乘法
/// </summary>
public class ChengFaCompute : Compute
{
public override int GetResult()
{
return number1 * number2;
}
} /// <summary>
/// 除法
/// </summary>
public class ChuFaCompute : Compute
{
public override int GetResult()
{
return number1 / number2;
}
}