Creational Design Pattern · Java

Abstract Factory Design Pattern in Java

Create families of related objects without coupling your application to concrete classes.

What is Abstract Factory?

Abstract Factory creates families of related objects without exposing their concrete classes. A theme factory, for example, can create a matching button and dialog for a light or dark user interface.

Simple theme example

First define contracts for the products in the family.

interface Button {
    void render();
}
interface Dialog {
    void render();
}

Then create one family of compatible products and a factory for that family.

class DarkButton implements Button {
    public void render() {
        System.out.println("Dark button");
    }
}

interface ThemeFactory {
    Button createButton();
    Dialog createDialog();
}

class DarkThemeFactory implements ThemeFactory {
    public Button createButton() {
        return new DarkButton();
    }
    public Dialog createDialog() {
        return new DarkDialog();
    }
}

The application uses ThemeFactory, so switching from dark products to light products does not change the application workflow.

Benefits and trade-offs

Benefits
  • Keeps related products compatible.
  • Hides concrete implementation classes.
  • Makes switching product families easy.
Trade-offs
  • Adding a product type changes every factory.
  • Can introduce many interfaces and classes.

When should you use it?

  • Your application supports multiple compatible product families.
  • Products must work together consistently.
  • You want to switch themes, environments, or platforms in one place.
Key takeawayAbstract Factory keeps related products compatible while allowing the whole product family to change behind one interface.