抽象工厂模式是工厂方法模式的升级,在有多个业务品种、业务分类时,通过抽象工厂模式产生需要的对象是一种非常好的解决方法。
抽象工厂的通用类图
抽象工厂模式使用于多个业务品种或者多个业务类型,即AbstractProduct存在多个实现类,拿生产手机为例。
可以生产诺基亚(由于可以砸核桃所以破产了),苹果、三星、小米、华为、锤子等,类图如下:
将上述的手机类图转化为代码如下:
/** * 手机的抽象类 * * * */ public abstract class AbstractMobile { // 每个手机都自己的型号 protected String model; // 每个手机都有自己的名字 protected String name; // 构造器 public AbstractMobile(String name, String model) { this.name = name; this.model = model; } // Method protected abstract void call(); }
public class Nokia extends AbstractMobile { /** * @param name * @param model */ public Nokia(String name, String model) { super(name, model); } /** * * @see com.huashao.chapter.chapter09.AbstractMobile#call() */ @Override protected void call() { System.out.println("来自诺基亚的呼叫"); } }
public class IPhone extends AbstractMobile { /** * @param name * @param model */ public IPhone(String name, String model) { super(name, model); // TODO Auto-generated constructor stub } /** * * @see com.huashao.chapter.chapter09.AbstractMobile#call() */ @Override protected void call() { System.out.println("来自苹果的呼叫"); } }
public class SamSung extends AbstractMobile { /** * @param name * @param model */ public SamSung(String name, String model) { super(name, model); // TODO Auto-generated constructor stub } /** * * @see com.huashao.chapter.chapter09.AbstractMobile#call() */ @Override protected void call() { System.out.println("来自三星的呼叫"); } }
那么如何生产三家手机厂商的手机呢,它总不能先生产诺基亚,生产完了再生产苹果吧,那苹果肯定不愿意啊,你诺基亚手机能砸核桃就了不起啊。直接上类图
一个抽象工厂对应三个工厂实现类,实现类01生产低配手机、实现类02生产高配手机、实现类03生产定制类手机,具体代码如下:
/** * 手机生产的抽象工厂 * */ public abstract class AbstractMobileFactory { // 生产诺基亚手机 public abstract AbstractMobile createNokia(); // 生产苹果手机 public abstract AbstractMobile createIPhone(); // 生产三星手机 public abstract AbstractMobile createSamsung(); }
实现类代码:
public class Mobile01Factory extends AbstractMobileFactory { /** * @return * @see com.huashao.chapter.chapter09.AbstractMobileFactory#createNokia() */ @Override public AbstractMobile createNokia() { // TODO Auto-generated method stub return new Nokia("诺基亚", "1010"); } /** * @return * @see com.huashao.chapter.chapter09.AbstractMobileFactory#createIPhone() */ @Override public AbstractMobile createIPhone() { // TODO Auto-generated method stub return new IPhone("iPhone", "3G"); } /** * @return * @see com.huashao.chapter.chapter09.AbstractMobileFactory#createSamsung() */ @Override public AbstractMobile createSamsung() { // TODO Auto-generated method stub return new SamSung("Samsung", "001"); } }
其他两个类的实现类似,在此不再赘述,其实我们看类图可以看到,工厂方法模式是抽象类之间的依赖,抽象工厂模式则是具体实现类之间的依赖,抽象工厂类适合的场景是一个产品族。
通过类图我们还能得到的就是抽象工厂方法的缺点就是产品族的扩展很困难,比如在现有代码上增加一个小米手机,你可以看看你的代码改动有多大,我们需要写一个小米类,同时抽象工厂方法里需要增加一个生产小米的抽象方法,同时工厂的实现类也需要改动。
相关链接:
http://www.cnblogs.com/java-my-life/archive/2012/03/28/2418836.html