工廠方法模式定義一個建立物件的介面,但由子類別決定實例化哪個具體類別。核心工廠類不再負責具體產品建立,轉而成為抽象工廠角色,僅定義子類必須實現的介面。這種「再抽象化」讓系統在不修改既有工廠程式碼的前提下引入新產品,完美符合開閉原則。
| 角色 | 說明 | 範例對應 |
|---|---|---|
| Creator (抽象工廠) | 核心介面,宣告工廠方法,與應用程式無關 | AbstractFactory |
| ConcreteCreator (具體工廠) | 實現工廠方法,包含應用相關邏輯,負責建立具體產品 | FactoryA, FactoryB |
| Product (抽象產品) | 產品物件的共同超型/介面 | Plant, Fruit |
| ConcreteProduct (具體產品) | 實現抽象產品介面,與特定工廠一一對應 | PlantA, FruitA |

// 抽象產品介面
public interface Plant { void doSomething(); }
public interface Fruit { void doSomething(); }
// 具體產品
public class PlantA implements Plant {
public PlantA() { System.out.println("create PlantA!"); }
public void doSomething() { System.out.println("PlantA do something..."); }
}
public class PlantB implements Plant { /* 類似實作 */ }
public class FruitA implements Fruit { /* 類似實作 */ }
public class FruitB implements Fruit { /* 類似實作 */ }
// 抽象工廠:定義多個工廠方法(對應多個產品族)
public interface AbstractFactory {
Plant createPlant();
Fruit createFruit();
}
// 具體工廠 A:生產 A 系列產品
public class FactoryA implements AbstractFactory {
public Plant createPlant() { return new PlantA(); }
public Fruit createFruit() { return new FruitA(); }
}
// 具體工廠 B:生產 B 系列產品
public class FactoryB implements AbstractFactory {
public Plant createPlant() { return new PlantB(); }
public Fruit createFruit() { return new FruitB(); }
}
public class Client {
public static void main(String[] args) {
AbstractFactory factory = new FactoryA(); // 或由配置/注入決定
Plant plant = factory.createPlant();
Fruit fruit = factory.createFruit();
plant.doSomething();
fruit.doSomething();
}
}
| 維度 | 簡單工廠 | 工廠方法 |
|---|---|---|
| 核心結構 | 單一具體工廠類,靜態方法判斷建立何種產品 | 抽象工廠介面 + 多個具體工廠子類 |
| 擴展新產品 | 需修改工廠類原始碼(違反開閉原則) | 新增具體工廠與產品類,無需動既有程式碼 |
| 多態性 | 無 | 具體工廠共享介面,支援多態替換 |
| 別名 | 靜態工廠模式 | 多態性工廠模式 |
工廠方法模式可視為簡單工廠的多態化演進;當系統僅有一種產品且極少變動時,簡單工廠足夠;若產品族擴展頻繁,工廠方法更適合。
本文範例中的 AbstractFactory 同時定義 createPlant() 與 createFruit(),實際上已展示抽象工廠模式的雛形——負責建立一組相關/相依產品(產品族)。純粹的工廠方法通常每個工廠只對應一個產品等級結構。
工廠方法模式將「什麼時候建立什麼物件」的決策權下放給子類,實現了框架與應用邏輯的解耦。它是許多框架(如 Spring 的 FactoryBean、JDBC 的 DriverManager、集合框架的 iterator())的基石設計。掌握其「抽象工廠介面 + 具體工廠實現」的雙層結構,是理解依賴倒置與控制反轉的關鍵一步。