Course contentsShow
← Software Engineering
Lesson 237 of 1,9337. Creational Design PatternsFree lesson

Abstract Factory Pattern: Intent and Structure

Provide an interface for creating families of related objects without specifying concrete classes.

Abstract Factory Pattern: Intent and Structure

What You'll Learn

You'll learn how the Abstract Factory pattern lets you create families of related objects without locking yourself into specific implementations.

The Core Problem and Solution

Imagine you're building a UI library that needs to support multiple themes (Light Mode and Dark Mode). Each theme needs its own set of components: buttons, checkboxes, text fields, etc. These components must work together visually—you can't mix a dark button with a light checkbox.

The Abstract Factory pattern provides an interface for creating families of related objects without your code needing to know the concrete classes. Instead of calling new DarkButton() or new LightCheckbox() directly, you ask a factory: "Give me a button" and "Give me a checkbox." The factory ensures you get a matching set.

The Structure

The pattern involves four key players:

  1. Abstract Factory Interface: Declares methods for creating each type of product (createButton(), createCheckbox())
  2. Concrete Factories: Implement the interface, creating products for a specific family (DarkThemeFactory, LightThemeFactory)
  3. Abstract Product Interfaces: Define what each product type can do (Button, Checkbox)
  4. Concrete Products: The actual implementations (DarkButton, LightButton, DarkCheckbox, LightCheckbox)

Why This Matters

Your client code works with the abstract factory and product interfaces only. Want to switch from dark to light theme? Just swap which factory you instantiate—no other code changes needed. This builds on the Dependency Inversion Principle you learned earlier: depend on abstractions, not concrete classes.

Key Takeaway: Abstract Factory ensures families of related objects are created together and remain compatible, while keeping client code decoupled from specific implementations.