工厂方法模式:定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
产生原因:简单工厂模式,如果添加新运算类就会影响开放-封闭原则。为了解决这个问题,采用工厂方法模式。
举例:计算器的加减乘除,如果添加一个新的运算类M的N次方类,简单工厂模式就会违反开放-封闭原则,这时候我们使用工厂方法模式。
简单工厂模式:
代码:
运算类:
public class Operation
{
private double _numberA = 0;
private double _numberB = 0;
public double NumberA
{
get { return _numberA; }
set { _numberA = value; }
}
public double NumberB
{
get { return _numberB; }
set { _numberB = value; }
}
public virtual double GetResult()
{
double result = 0;
return result;
}
}
加减乘除类:
class OperationAdd : Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA + NumberB;
return result;
}
}
class OperationSub : Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA - NumberB;
return result;
}
}
class OperationMul : Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA * NumberB;
return result;
}
}
class OperationDiv : Operation
{
public override double GetResult()
{
double result = 0;
if (NumberB == 0)
throw new Exception("除数不能为0.");
result = NumberA / NumberB;
return result;
}
}
简单运算工厂类:
class OperationFactory
{
public static Operation createOperate(string operate)
{
Operation oper = null;
switch (operate)
{
case "+":
oper = new OperationAdd();
break;
case "-":
oper = new OperationSub();
break;
case "*":
oper = new OperationMul();
break;
case "/":
oper = new OperationDiv();
break;
}
return oper;
}
}
客户端代码:
static void Main(string[] args)
{
Operation oper;
oper = OperationFactory.createOperate("+");
oper.NumberA = 1;
oper.NumberB = 2;
double result = oper.GetResult();
Console.WriteLine(result);
Console.ReadKey();
}
工厂方法模式:
工厂接口:
interface IFactory
{
Operation CreateOperation();
}
具体工厂:
class AddFactory:IFactory
{
public Operation CreateOperation()
{
return new OperationAdd();
}
}
class SubFactory:IFactory
{
public Operation CreateOperation()
{
return new OperationSub();
}
}
class MulFactory:IFactory
{
public Operation CreateOperation()
{
return new OperationMul();
}
}
class DivFacory:IFactory
{
public Operation CreateOperation()
{
return new OperationDiv();
}
}
客户端:
static void Main(string[] args)
{
IFactory operFactory = new AddFactory();
Operation oper = operFactory.CreateOperation();
oper.NumberA = 1;
oper.NumberB = 2;
double result = oper.GetResult();
Console.WriteLine(result);
Console.ReadKey();
}
分析:简单工厂模式的最大优点在于工厂类中包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类,对于客户端来说,去除了与具体产品的依赖。在客户端,我们如果计算加法,只需选择+。
而工厂方法模式是简单工厂模式的进一步抽象和推广,它把简单工厂的内部逻辑判断移到了客户端代码来进行。原本是改工厂类,现在是修改客户端。 由于使用了多态性,工厂方法模式保持了简单工厂模式的优点。当添加新运算类时,整个工厂和产品体系都没有修改的变化,只是扩展的变化,从而克服了简单工厂模式的缺点。工厂方法模式的缺点:每加一个产品,就需要加一个产品工厂的类,增加了代码量。
这两种模式都几种封装了对象的创建,要改为减法时,不需要做大改动就可以实现,降低了客户程序与产品对象的耦合。