工廠方法模式屬於創建型模式,定義為:定義一個用於創建對象的介面,讓子類決定實例化哪一個類,工廠方法使一個類的實例化延遲到其子類。
按抽象程度分:

interface IProduct { void productMethod(); }
class Product implements IProduct { public void productMethod() { System.out.println("產品"); } }
interface IFactory { IProduct createProduct(); }
class Factory implements IFactory { public IProduct createProduct() { return new Product(); } }
public class Client {
public static void main(String[] args) {
IFactory factory = new Factory();
IProduct product = factory.createProduct();
product.productMethod();
}
}
new 即可,別過度設計)。無工廠:Client 直接 new Engine()、new Wheel()、new Car(...),高耦合、難擴展、違反迪米特法則。
有工廠:Client 僅依賴 IFactory,Factory.createCar() 內部封裝組裝邏輯,耦合度大幅降低,擴展只需新增 Factory 實現。
工廠方法模式是「解耦利器」,將實例化延遲到子類,讓調用者專注於業務邏輯而非對象構建細節。掌握其與簡單工廠、抽象工廠的邊界,靈活選型。