抽象工廠模式是工廠方法模式的升級,在有多個業務品種、業務分類時,通過抽象工廠模式產生需要的對象是一種非常好的解決方法。
抽象工廠的通用類圖
抽象工廠模式使用於多個業務品種或者多個業務類型,即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