Implement Abstract Factory in Java when several related products must vary together under one stable client contract.
Abstract Factory: A factory interface that creates multiple related product types as a coordinated family.
Abstract Factory is useful when one choice should determine several compatible objects. The client does not merely need “a button” or “a formatter.” It needs a set of collaborators that belong together.
UI theming is the classic example because the products come in families:
1interface Button {
2 void render();
3}
4
5interface Checkbox {
6 void render();
7}
8
9interface WidgetFactory {
10 Button createButton();
11 Checkbox createCheckbox();
12}
13
14final class LightWidgetFactory implements WidgetFactory {
15 @Override
16 public Button createButton() {
17 return new LightButton();
18 }
19
20 @Override
21 public Checkbox createCheckbox() {
22 return new LightCheckbox();
23 }
24}
The client depends on WidgetFactory, Button, and Checkbox, not on the light or dark implementations directly.
The pattern keeps family selection in one place. That gives you:
If the codebase otherwise keeps saying “if dark mode, use this button and that checkbox,” the family logic is leaking.
Abstract Factory is heavier than Factory Method. It becomes the wrong trade when:
The pattern is powerful because it coordinates variation. If there is no real coordinated variation, the extra interfaces do not pay for themselves.
When reviewing an Abstract Factory in Java, ask:
Good Abstract Factory design makes families explicit. Bad Abstract Factory design invents families after the fact just to justify the pattern.