Abstract Factory
Create families of related objects without specifying their concrete classes — the factory guarantees everything it produces is compatible with each other.
Intent & Description
🎯 Intent
Produce sets of related objects that are designed to work together, with one factory per ’theme’ or ‘family’.
📋 Context
You’re building a cross-platform UI toolkit that needs to render Windows-style or Mac-style components. A Windows Button should pair with a Windows Checkbox — mixing platforms breaks the visual consistency. You need a way to swap the entire family at once.
💡 Solution
Define an Abstract Factory interface with methods like createButton(), createCheckbox(). Implement concrete factories per family (WinFactory, MacFactory). Client code uses the factory interface — it gets back compatible products regardless of which factory was injected.
Real-world Use Case
Source
📌 TL;DR
One factory, one compatible family. Swap the factory, swap the family. Adding a new product type means updating every factory. Great for themes and platform families.
Advantages
- Products from the same factory are guaranteed to work together.
- Swap the entire product family by swapping the factory.
- Client code never imports concrete product classes — fully decoupled.
Disadvantages
- Adding a new product type (e.g., a new widget) requires updating every factory implementation.
// Abstract Factory
class GUIFactory {
createButton() {}
createCheckbox() {}
}
// Concrete Factories
class WinFactory extends GUIFactory {
createButton() { return { paint: () => "Windows Button" }; }
createCheckbox() { return { paint: () => "Windows Checkbox" }; }
}
class MacFactory extends GUIFactory {
createButton() { return { paint: () => "Mac Button" }; }
createCheckbox() { return { paint: () => "Mac Checkbox" }; }
}