Abstract Factory Design Pattern — Java Example
Pattern: Creational → Abstract Factory Article: https://ankurm.com/abstract-factory-design-pattern-java/
What this example shows
A UI toolkit that produces families of related widgets — light theme or dark theme — without the client ever naming a concrete class. Button and TextField are abstract products; LightButton/LightTextField and DarkButton/DarkTextField are the two concrete product families. UIFactory declares the creation methods for the whole family; LightThemeFactory and DarkThemeFactory each produce one consistent family. Application is the client — it only depends on UIFactory and the abstract products, so swapping the entire theme is a one-line change. Main selects the factory via a system property.
How to run
javac abstract-factory/*.java -d out/abstract-factory
java -cp out/abstract-factory abstractfactory.Main
# or, for the dark theme family:
java -Dapp.theme=dark -cp out/abstract-factory abstractfactory.Main
Requires Java 25.
Post Section ↔ File Mapping
| Post Section | File(s) |
|---|---|
| Part 1 — The Abstract Products: Button and TextField | Button.java, TextField.java |
| Part 2 — The Concrete Products (Light family) | LightButton.java, LightTextField.java |
| Part 2 — The Concrete Products (Dark family) | DarkButton.java, DarkTextField.java |
| Part 3 — The Abstract Factory: UIFactory Interface | UIFactory.java |
| Part 4 — The Concrete Factories | LightThemeFactory.java, DarkThemeFactory.java |
| Part 5 — The Client: Application | Application.java, Main.java |
Article: https://ankurm.com/abstract-factory-design-pattern-java/ All patterns: https://ankurm.com/design-patterns-java/