简单工厂模式的不足
在简单工厂模式中,只提供了一个工厂类,该工厂类处于对产品类进行实例化的中心位置,它知道每个产品对象的创建细节,并决定何时实例化哪个产品类。简单工厂模式的最大的缺点是有当有新产品要加入系统中时,必须修改工厂类,加入必要的处理逻辑,这违背了”开闭原则“。在简单工厂模式中,所有的产品都是由同一个工厂创建,工厂类职责较重,业务逻辑较为复杂,具体产品与工厂类之间耦合度高,严重影响了系统的灵活性和扩展性,而工厂方法模式则可以很好的解决这个问题。
在软件系统中,经常面临着“某个对象”的创建工作,由于需求的变化,这个对象的具体实现经常面临着剧烈的变化,但它却拥有比较稳定的接口。如何应对这种变化?提供一种封装机制来隔离出“这个易变对象”的变化,从而保持系统中“其它依赖该对象的对象”不随着需求的改变而改变?这就是要说的Factory Method模式了。
下面的代码是对之前学习简单工厂模式时的实现加减乘除例子用工厂方法模式进行的优化:
using System; namespace LearnObject { 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; } } public class OperationAdd : Operation { public override double GetResult() { double result = 0; result = NumberA + NumberB; return result; } } public class OperationSub : Operation { public override double GetResult() { double result = 0; result = NumberA - NumberB; return result; } } public class OperationMul : Operation { public override double GetResult() { return NumberA * NumberB; } } public class OperationDiv : Operation { public override double GetResult() { if (NumberB == 0) { throw new Exception("除数不为零"); } return NumberA / NumberB; } } public interface IFactory { public Operation CreateOperation(); } public class AddFactory : IFactory { public Operation CreateOperation() { return new OperationAdd(); } } public class SubFactory : IFactory { public Operation CreateOperation() { return new OperationSub(); } } public class MulFactory : IFactory { public Operation CreateOperation() { return new OperationMul(); } } public class DivFactoru : IFactory { public Operation CreateOperation() { return new OperationDiv(); } } class Program { 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={0}", result); operFactory = new MulFactory(); oper = operFactory.CreateOperation(); oper.NumberA = 2; oper.NumberB = 3; result = oper.GetResult(); Console.WriteLine("mul result = {0}",result); } } }