工厂方法
工厂方法是简单工厂的一种扩展,一种衍生。相对于简单工厂,工厂方法一些意义上解决了简单工厂违背‘开放封闭原则’。那么让我们来看看工厂方法是怎么从简单工厂演化过来的吧。
我们先来看看简单工厂的类图:
从类图中我们可以看出,SimpleFactory类的任务艰巨。它内部有动态创建哪个具体产品类(Product)的功能。这样其实对用户来说操作简单了不少。但是如果要新增具体产品类时,简单工厂就有麻烦了,我们只能要先写一个具体产品类(Product_C)实现IProduct类,再在SimpleFactory里面修改代码,把创建具体产品类(Product_C)的逻辑代码写进去。这就是为什么简单工厂违背了‘开放封闭原则’的原因。那工厂方法是怎么解决简单工厂的这个不足之处的呢?让我们先来看看工厂方法的类图:
从工厂方法的类图中,我们看到其实工厂方法把简单工厂中工厂的逻辑处理延迟到了它的具体子类中去创建具体类(Product)。这样如果要新增具体产品类(Product)时,就不用修改工厂类了,只要写一个具体工厂类并实现IFactory接口就可以了。这样是不是比简单工厂灵活多了,恩,是的。。。。。
C#代码:
抽象工厂类:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Design_Mode.Factory_Method { public interface IFactory { IProduct factory(); } }
具体工厂类A:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Design_Mode.Factory_Method { class Factory_A : IFactory { #region IFactory 成员 public IProduct factory() { return new Product_A(); } #endregion } }
具体工厂类B:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Design_Mode.Factory_Method { class Factory_B : IFactory { #region IFactory 成员 public IProduct factory() { return new Product_B(); } #endregion } }
抽象产品类:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Design_Mode.Factory_Method { public interface IProduct { void operation(); } }
具体产品类A:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Design_Mode.Factory_Method { class Product_A : IProduct { #region IProduct 成员 public void operation() { Console.Write("Product_A\n"); } #endregion } }
具体产品类B:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Design_Mode.Factory_Method { class Product_B : IProduct { #region IProduct 成员 public void operation() { Console.Write("Product_B\n"); } #endregion } }
客户端测试代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; //using Design_Mode.Simple_Factory; using Design_Mode.Factory_Method; namespace Design_Mode { class Program { static void Main(string[] args) { #region 简单工厂 例子 //IProduct product = SimpleFactory.factory("A"); //if(product != null) // product.operation(); #endregion #region 工厂方法例子 IFactory factory = new Factory_A(); IProduct product = factory.factory(); if (product != null) product.operation(); #endregion } } }
优点:相对于简单工厂,工厂在新增具体产品类时,通过延迟创建具体产品类到工厂子类的方法来解决了‘开放封闭原则’。
缺点:相对于简单工厂,工厂方法暴露给用户的类相对增加了,有IFactory和一系列的具体工厂类,还有IProduct类。但是增加其他系列的产品时,工厂方法并没有解决问题。
展望:我们可以结合抽象工厂来实现动态增加其他系列的产品。