Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 57 ยท Creational Patterns

Abstract Factory

Learn the Abstract Factory design pattern: build families of related objects, such as a UI theme kit, and swap the whole family at runtime.

The Abstract Factory pattern provides an interface for creating a whole family of related objects without naming their concrete classes. Instead of one factory method that returns one product, you get a factory object with several creation methods (createButton(), createCheckbox(), createDialog()), and each concrete factory produces a matching set.

The point is consistency. If your app has a light theme and a dark theme, you never want a dark button inside a light dialog. If it talks to either PostgreSQL or SQLite, you never want a PostgreSQL connection paired with a SQLite query builder. Abstract Factory guarantees that the pieces you receive were designed to work together, and it lets you switch the entire family by changing a single object. It builds on Factory Method and follows the Dependency Inversion Principle.

The cast of characters

Abstract factory Lists one create method per product kind.
Concrete factory Builds one complete family, such as Dark.
Abstract products Button, Checkbox, Dialog interfaces.
Concrete products DarkButton, LightButton, and so on.

The client sees only the abstract factory and abstract products.

1 / 2

The structure

There are two dimensions: product kinds (button, checkbox) and families (light, dark). Every family implements every product kind. The abstract factory declares one creation method per kind, and each concrete factory implements them all for its family.

classDiagram
    class UiFactory {
        <<interface>>
        +createButton() Button
        +createCheckbox() Checkbox
    }
    class LightFactory
    class DarkFactory
    class Button {
        <<interface>>
        +render() string
    }
    class Checkbox {
        <<interface>>
        +render() string
    }
    UiFactory <|.. LightFactory
    UiFactory <|.. DarkFactory
    Button <|.. LightButton
    Button <|.. DarkButton
    Checkbox <|.. LightCheckbox
    Checkbox <|.. DarkCheckbox
    LightFactory ..> LightButton : creates
    LightFactory ..> LightCheckbox : creates
    DarkFactory ..> DarkButton : creates
    DarkFactory ..> DarkCheckbox : creates

Each concrete factory creates one button and one checkbox from the same family.

In Java this is usually written with interfaces; in C++ with abstract classes that have pure virtual functions. The idea is identical in every language. Here is the Java shape, read-only, to show the vocabulary:

Java
interface Button { String render(); }
interface Checkbox { String render(); }

interface UiFactory {
    Button createButton(String label);
    Checkbox createCheckbox(String label);
}

class DarkFactory implements UiFactory {
    public Button createButton(String label) { return new DarkButton(label); }
    public Checkbox createCheckbox(String label) { return new DarkCheckbox(label); }
}

class Screen {
    private final UiFactory factory;          // the only thing Screen knows
    Screen(UiFactory factory) { this.factory = factory; }
    String build() {
        return factory.createButton("Save").render()
             + factory.createCheckbox("Remember me").render();
    }
}

Notice that Screen never mentions DarkButton. That is the whole trick.

A UI theme factory you can run

The JavaScript version below is a runnable stand-in for the Java sketch. Products return plain strings so the output is easy to read; a real toolkit would return DOM elements or native widgets. JavaScript has no interfaces, so the "abstract" types are a convention: any object with a render() method counts.

JS Light and dark theme families

Press Run (or Ctrl + Enter) to see the console output here.

No output.

buildLoginForm was written once and works with both families. Adding a third family, say a high-contrast theme, means writing its products and a HighContrastFactory. No existing class changes, which is the Open/Closed Principle at work.

Swapping families at runtime

Because the client holds the factory in a variable, you can replace the factory while the program runs. A settings screen can switch the theme and rebuild everything from the new factory. The one rule to keep is that you must rebuild: objects already created still belong to the old family.

JS Switching the whole family at runtime

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Two details are worth noticing. First, the factories here are plain objects of functions; in JavaScript, Python and other languages with first-class functions you do not need a class per factory. A dictionary or object of creators is a perfectly good Abstract Factory. Second, the broken factory fails with a TypeError the first time something calls a missing method, and the app keeps its previous widgets because the assignment to #widgets never happened. In a statically typed language the compiler would reject the incomplete factory before the program ran.

Where it appears in real code

  • GUI toolkits: one set of widget classes per operating system or theme.
  • Database access: a family of connection, command and transaction objects for each database vendor.
  • Cross-platform games: renderer, audio device and input handler for each platform.
  • Test doubles: a FakeServicesFactory that builds in-memory versions of every service, so a whole test setup is swapped at once.

Trade-offs and pitfalls

The biggest cost is adding a new product kind. If you add createSlider() to the abstract factory, every concrete factory in every family must be edited. The pattern makes new families cheap and new kinds expensive. If you expect the kinds to change often and the families rarely, a different design suits you better.

It also multiplies class counts: K kinds times F families means K x F product classes plus F factories. Languages with closures and dictionaries shrink this a lot, as the second example showed.

Finally, do not use it for unrelated objects. A factory that makes a Logger, a PdfRenderer and a TaxCalculator is not a family; it is a grab bag, and a plain dependency injection container expresses that better.

Compare the neighbors: Factory Method creates one product; Abstract Factory creates a family; Builder assembles one complicated object step by step. Abstract factories are often implemented as a set of factory methods, and each concrete factory is frequently a Singleton, since one instance is enough.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does an Abstract Factory create?

    Abstract Factory groups several creation methods so that a consistent set of related products is produced together.
  2. 2. Which change is most expensive in a design that uses Abstract Factory?

    A new kind requires a new method on the abstract factory and an implementation in every concrete factory. A new family only needs new classes.
  3. 3. Why should the client code depend only on the abstract factory and abstract products?

    Depending on abstractions keeps the client unaware of concrete classes, which is what makes families interchangeable.
  4. 4. After switching to a different factory at runtime, what must you do?

    A factory only affects objects created after the swap, so the client must rebuild anything that should use the new family.
  5. 5. Which description best separates Abstract Factory from Factory Method?

    Factory Method is one overridable creation method. Abstract Factory is a set of them that together produce a consistent family.

Summary

  • Abstract Factory creates families of related objects through an interface with one creation method per product kind.
  • Concrete factories each produce one complete family, so mismatched combinations cannot occur.
  • The client depends only on abstractions, so swapping the factory swaps the whole family; rebuild existing objects after a swap.
  • New families are cheap to add, new product kinds are expensive.
  • In JavaScript and Python an object or dictionary of creator functions often replaces the class hierarchy.

Next lesson: Builder.