一、简单工厂模式简介(Bref Introduction)
二、解决的问题(What To Solve)
三、简单工厂模式分析(Analysis)
1、简单工厂模式结构
四.实例分析(Example)
1、场景
2、代码
1、抽象操作类Operation,及其具体实现类AddOperation、SubOperation |
/// <summary>
/// 抽象操作类
/// </summary>
public abstract class Operation
{
public int numberA;
public int numberB;
public abstract int GetResult();
}
/// <summary>
/// 加法操作
/// </summary>
public class AddOperation : Operation
{
public override int GetResult()
{
return (this.numberA + this.numberB);
}
}
/// <summary>
/// 减法操作
/// </summary>
public class SubOperation : Operation
{
public override int GetResult()
{
return (this.numberA - this.numberB);
}
} |
2、简单工厂类SimpleFactory |
/// <summary>
/// 简单工厂类
/// </summary>
public class SimpleFactory
{
public static Operation CreateOperation(string operation)
{
Operation o = null;
switch (operation)
{
case "+":
o = new AddOperation();
break;
case "-":
o = new SubOperation();
break;
}
return o;
}
} |
3、客户端代码 |
static void
{
Operation operation1 = SimpleFactory.CreateOperation("+");
operation1.numberA = 10;
operation1.numberB = 20;
Console.WriteLine("{0}+{1}={2}", operation1.numberA, operation1.numberB, operation1.GetResult());
Operation operation2 = SimpleFactory.CreateOperation("-");
operation2.numberA = 10;
operation2.numberB = 20;
Console.WriteLine("{0}-{1}={2}", operation2.numberA, operation2.numberB, operation2.GetResult());
Console.Read();
} |