On this page
Abstract Factory
The Abstract Factory pattern provides an interface for creating families of related objects without specifying their concrete classes.
Problem
You need to create groups of related products (UI components, database drivers) that must be compatible with each other.
Solution
// Abstract products
interface Button { void render(); }
interface Checkbox { void render(); }
// Abstract factory
interface GUIFactory {
Button createButton();
Checkbox createCheckbox();
}
// Concrete factories
class WindowsFactory implements GUIFactory {
public Button createButton() { return new WindowsButton(); }
public Checkbox createCheckbox() { return new WindowsCheckbox(); }
}
class MacFactory implements GUIFactory {
public Button createButton() { return new MacButton(); }
public Checkbox createCheckbox() { return new MacCheckbox(); }
}
// Client code
class Application {
private final GUIFactory factory;
Application(GUIFactory factory) {
this.factory = factory;
}
void renderUI() {
Button button = factory.createButton();
Checkbox checkbox = factory.createCheckbox();
button.render();
checkbox.render();
}
}
Java Examples
// DocumentBuilderFactory creates a family of XML parsing objects
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(inputStream);
// Connection pool factories
DataSource mysql = createFactory("mysql").createDataSource(config);
DataSource postgres = createFactory("postgres").createDataSource(config);
Abstract Factory vs Factory Method
| Abstract Factory | Factory Method |
|---|---|
| Creates families of related objects | Creates one type of object |
| Multiple factory methods | Single factory method |
| Composition of products | Inheritance-based |
When to Use
- System must be independent of how products are created
- Products must be used together (same family/theme)
- You want to swap entire product families at runtime
Best Practices
- Inject the abstract factory via constructor — do not hardcode concrete factories
- Keep product interfaces small and focused
- Use with dependency injection frameworks for runtime factory selection
- Consider whether simpler patterns (Factory Method, Strategy) suffice first