GoF pattern • Creational
GoFCreationalJava example
Abstract Factory solves a specific structural problem in the design.
Create related objects without hard-coding their concrete classes.
Pattern overview
GoF pattern
Create related objects without hard-coding their concrete classes.
Intent
Provide an interface for creating families of related objects while keeping client code independent from concrete implementations.
Problem
A system needs to swap whole families of related objects together, and direct instantiation would spread environment-specific decisions everywhere.
Solution
Centralize family creation behind a factory interface so clients request abstract products instead of constructing concrete ones directly.
Fit and tradeoffs
FamilyGoF
CategoryCreational
Best used when
- When you have multiple platform, theme, or vendor-specific object families.
- When products must be used together consistently.
- When you want to isolate construction logic from domain logic.
Tradeoffs
- Adds more interfaces and classes up front.
- Can feel heavyweight if there is only one product family.
Java example
This example is intentionally compact so the pattern shape stays easy to see.
interface Button {
String render();
}
interface Dialog {
String render();
}
interface UiFactory {
Button createButton();
Dialog createDialog();
}
final class WebUiFactory implements UiFactory {
public Button createButton() { return () -> "<button>Save</button>"; }
public Dialog createDialog() { return () -> "<dialog>Settings</dialog>"; }
}
final class DesktopUiFactory implements UiFactory {
public Button createButton() { return () -> "[Save Button]"; }
public Dialog createDialog() { return () -> "[Settings Dialog]"; }
}