設計模式是軟件工程中解決特定問題的經典方案,而工廠模式作為創建型模式的代表,在Java開發中應用廣泛。本文結合B站尚硅谷課程精華,系統工廠模式的三種形式,輔以圖解和代碼實戰,并探討其在項目策劃與公關服務系統中的實際應用。
一、工廠模式概述
工廠模式的核心思想是將對象的創建與使用分離,通過一個統一的接口來創建對象,降低客戶端與具體產品類之間的耦合度。它主要分為三種形式:簡單工廠模式、工廠方法模式和抽象工廠模式。
二、三種工廠模式詳解與圖解
1. 簡單工廠模式(Simple Factory)
- 結構圖:客戶端 → 工廠類(根據參數創建產品) → 具體產品A/B
- 特點:一個工廠類負責所有產品的創建,通過傳入不同參數返回不同對象。
- 代碼示例:`java
public class ProductFactory {
public static Product createProduct(String type) {
if ("A".equals(type)) return new ConcreteProductA();
if ("B".equals(type)) return new ConcreteProductB();
throw new IllegalArgumentException("Unknown product type");
}
}`
- 優缺點:結構簡單,但違反開閉原則(新增產品需修改工廠類)。
2. 工廠方法模式(Factory Method)
- 結構圖:客戶端 → 抽象工廠(聲明創建方法) → 具體工廠A/B(各自創建對應產品) → 具體產品A/B
- 特點:每個產品對應一個工廠類,符合開閉原則。
- 代碼示例:`java
interface Factory {
Product createProduct();
}
class FactoryA implements Factory {
public Product createProduct() { return new ProductA(); }
}`
- 優缺點:擴展性好,但類數量增多。
3. 抽象工廠模式(Abstract Factory)
- 結構圖:客戶端 → 抽象工廠(聲明多個創建方法) → 具體工廠1/2(創建產品族) → 產品族A/B(包含多個關聯產品)
- 特點:用于創建一系列相關或依賴的對象,強調產品族概念。
- 代碼示例:`java
interface AbstractFactory {
Report createReport();
Poster createPoster();
}
class PRFactory implements AbstractFactory {
public Report createReport() { return new PRReport(); }
public Poster createPoster() { return new PRPoster(); }
}`
- 優缺點:保證產品族一致性,但擴展產品族困難。
三、小項目實戰:公關服務系統設計
假設我們開發一個公關服務系統,需要生成不同類型的報告和宣傳材料。
1. 需求分析:
- 報告類型:輿情報告、活動報告
- 宣傳材料:海報、新聞稿
- 客戶類型:企業客戶、政府客戶(不同客戶需要風格一致的材料族)
2. 代碼實現(抽象工廠模式應用):`java
// 抽象產品
interface Report { void generate(); }
interface Poster { void design(); }
// 具體產品
class EnterpriseReport implements Report {
public void generate() { System.out.println("生成企業版報告"); }
}
class GovernmentPoster implements Poster {
public void design() { System.out.println("設計政府風格海報"); }
}
// 抽象工廠
interface PRFactory {
Report createReport();
Poster createPoster();
}
// 具體工廠
class EnterpriseFactory implements PRFactory {
public Report createReport() { return new EnterpriseReport(); }
public Poster createPoster() { return new EnterprisePoster(); }
}
// 客戶端使用
public class Client {
public static void main(String[] args) {
PRFactory factory = new EnterpriseFactory();
Report report = factory.createReport();
Poster poster = factory.createPoster();
report.generate();
poster.design();
}
}`
3. 項目策劃中的模式選擇:
- 初期產品單一:可使用簡單工廠模式快速原型開發
- 產品線擴展:采用工廠方法模式便于新增產品類型
- 多套風格系統:抽象工廠模式確保企業/政府客戶材料的整體一致性
四、與最佳實踐
- 簡單工廠適用于產品類型少、變化不大的場景
- 工廠方法是Spring框架中BeanFactory的思想基礎,支持靈活擴展
- 抽象工廠在UI主題切換、跨平臺產品族創建中優勢明顯
- 在公關服務系統中:
- 利用工廠模式統一管理宣傳材料生成
- 通過配置化選擇工廠,輕松切換服務風格
- 新增客戶類型時只需擴展工廠類,不影響現有代碼
工廠模式不僅是代碼設計工具,更是項目策劃中的架構思維。理解其精髓,能在復雜系統設計中游刃有余,提升代碼的可維護性和擴展性。