比如我们写一个加减乘除的计算类,按正常来写的话一定是
public Class Operation
{
public Add(int a, int b);
public Sub(int a, int b);
public Mul(int a, int b);
public Dev(int a, int b);
}
或者是
public Class Operation
{
public double Caculate(double a, double, String caculate)
{
switch(caculate)
{
case:"+"
return a+b;
...
...
}
}
}
直接实例化Operation就直接用了,或者有为了方便的直接把方法写成static的。
虽然这样写已经可以了,但是问题来了,如何让计算器知道我是想用哪一个方法呢?
简单工厂模式
我们应该考虑用一个单独的类来做这个创造实例的过程,这就是工厂。
public class OperationFactory
{
public static Operation CreateOperate(String Operation)
{
Operation operation = null;
switch (operation)
{
case "+":
operation = new OperationAdd();
break;
case "-":
operation = new OperationSub();
break;
case "*":
operation = new OperationMul();
break;
case "/":
operation = new OperationDiv();
break;
}
return operation;
}
}
现在只需要输入运算符号,工厂就能实例化出合适的对象。
客户端代码
Operation operation;
opeartion = OperationFactory.createOperate("+");
operation.NumberA = 1;
operation.NumberB = 2;
double result = operation.GetResult();
优点:
根据外界给定的信息,决定究竟应该创建哪个具体类的对象。
缺点:
高内聚,所有创建逻辑集中到工厂类。