# Abstract FactoryA photo is saved on a laptop while its thumbnail job goes to the cloud: file not found. Learn how one factory per family keeps related objects matching, what it costs, and when to skip it.

A user uploads a photo, and the app says: saved. A minute later, the thumbnail worker says: file not
found. Each setting was fine on its own. Together, they don't match. So who makes sure the pieces
match? That's the job of the **Abstract Factory** pattern.

Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows
it section by section, with diagrams and a little extra depth.

{{< lesson-video youtube="hHsW2_N4Cjs" title="Abstract Factory" >}}

## Saved, then file not found

Here's what happened. On a developer's laptop, storage was switched to the local disk. But the
thumbnail job still went to the real cloud queue. A worker in the cloud picked up the job, and
looked for a file that only exists on that laptop.

```mermaid {alt="The photo is saved to the laptop's local disk (storage = local), but the thumbnail job goes to the cloud queue (queue = cloud). The cloud worker looks for the file and fails: file not found." caption="Two settings, each fine on its own, that don't match."}
flowchart TD
  P["photo"] --> D["laptop disk<br/>storage = local"]
  P --> Q["cloud queue<br/>queue = cloud"]
  Q --> W["cloud worker"]
  W -.->|"looks for the file"| D
  W --> X["file not found"]
  class D c6
  class Q,W c4
  class X bad
```

Related objects chosen separately can end up from different worlds.

## Chess sets

Picture two chess sets: one carved from wood, one made of glass. Both have the same kinds of pieces,
a king and pawns. Nobody plays with a glass king and wooden pawns. You pick a set, and every piece
comes from it. And switching sets switches every piece at once. You never swap the pawns one by one.

In the pattern's words, a kind of piece is a **product**. One set's pieces are a **family**. And the
set maker you ask for pieces is the **factory**. Keep one more thing in mind: if a new version of
the game adds a new kind of piece, every set maker has to carve one. It comes back later.

```mermaid {alt="The chess analogy mapped onto code: the set maker is the factory (Platform); one set is a family (LocalPlatform or CloudPlatform); a kind of piece is a product (Storage, JobQueue)." caption="Pick the set, and the pieces follow."}
flowchart LR
  A["set maker"] --> A2["factory: Platform"]
  B["one set (wood, glass)"] --> B2["family: LocalPlatform, CloudPlatform"]
  C["kind of piece (king, pawn)"] --> C2["product: Storage, JobQueue"]
  class A2 c1
  class B2 c4
  class C2 c5
```

## The obvious version: each class picks its own

The upload service picks its storage from a setting: the local disk, or a bucket in the cloud. The
thumbnail worker does the same for its queue, with a setting of its own.

```java
// in UploadService
Storage storage = config.is("storage", "local")
        ? new DiskStorage() : new BucketStorage();

// in ThumbnailWorker
JobQueue queue = config.is("queue", "local")
        ? new MemoryQueue() : new CloudQueue();
```

And that's fair. Each choice is one readable line, right where it's used, and it works. Both
settings default to the cloud, and in production that's exactly right. The trouble starts the day
someone changes only one of them.

## Why it breaks

Two settings give four combinations, and only two of them make sense. Nothing stops the other two.

| storage \ queue | local | cloud |
|---|---|---|
| **local** | matches | the bug from the start |
| **cloud** | mismatch | matches |

Every new piece adds a setting and another `if`: a cache, an email sender. Each one can end up in
the wrong world. And a third setup, say for tests, means finding and editing every one of those
`if`s. It's like every player grabbing a piece from whichever set is nearest. Most games look fine,
until one doesn't.

```mermaid {alt="Each new piece adds a setting and an if in some class: storage, queue, cache and mail settings each pick local or cloud independently, and a new test setup has to touch every one of those ifs." caption="Pieces chosen one by one: every setting is a chance to mismatch."}
flowchart TD
  T["new setup: test"] --> S["storage if"]
  T --> Q["queue if"]
  T --> C["cache if"]
  T --> M["mail if"]
  class T warn
  class S,Q,C,M bad
```

## The key idea: one object chooses the family

So don't let each class choose its piece. Make one object that knows the whole set, and ask it for
every piece. In code, that's an interface with one create method for each kind of product.

```java
public interface Platform {
    Storage createStorage();
    JobQueue createQueue();
}
```

Notice that nothing here says cloud or local. The interface names the kinds of pieces, and leaves
the family open. The Gang of Four state the intent like this: "Provide an interface for creating
families of related or dependent objects without specifying their concrete classes."

> **Choose the set, not the pieces.**

## Building it: one class per family

Each family becomes one small class. The cloud platform makes bucket storage and the cloud queue.
The local platform makes disk storage and a queue that lives in memory.

```java
public class CloudPlatform implements Platform {
    public Storage createStorage() { return new BucketStorage(); }
    public JobQueue createQueue() { return new CloudQueue(); }
}

public class LocalPlatform implements Platform {
    public Storage createStorage() { return new DiskStorage(); }
    public JobQueue createQueue() { return new MemoryQueue(); }
}
```

Now `PhotoUploads` takes a platform in its constructor, and asks it for both pieces. It never names
a concrete class.

```java
public class PhotoUploads {
    private final Storage storage;
    private final JobQueue queue;

    public PhotoUploads(Platform platform) {
        this.storage = platform.createStorage();
        this.queue = platform.createQueue();
    }
}
```

The choice is made once, in `main`:

```java
Platform platform = config.is("env", "local")
        ? new LocalPlatform() : new CloudPlatform();
PhotoUploads uploads = new PhotoUploads(platform);
```

And a test passes the local platform, with no cloud at all:

```java
PhotoUploads uploads = new PhotoUploads(new LocalPlatform());
```

Now the bug from the start can't happen. Storage and queue always come from the same family. Notice
what moved: the `if`s didn't disappear. They shrank to one, in `main`, where the program is put
together.

```mermaid {alt="Sequence: main creates a LocalPlatform or CloudPlatform once and passes it to PhotoUploads; PhotoUploads calls createStorage and createQueue on it and gets both pieces from the same family." caption="One choice in main; every piece follows it."}
sequenceDiagram
  participant M as main
  participant P as Platform
  participant U as PhotoUploads
  M->>P: new LocalPlatform() or new CloudPlatform()
  M->>U: new PhotoUploads(platform)
  U->>P: createStorage()
  P-->>U: Storage (same family)
  U->>P: createQueue()
  P-->>U: JobQueue (same family)
```

## The parts

`Platform` is the **abstract factory**. The cloud and local platforms are **concrete factories**.
`Storage` and `JobQueue` are the **abstract products**; `BucketStorage`, `DiskStorage` and the rest
are the **concrete products**. And `PhotoUploads` is the **client**: it only ever sees the
interfaces, so it can't pick the wrong concrete class.

```mermaid {alt="Class diagram: PhotoUploads uses the Platform interface and the Storage and JobQueue interfaces. CloudPlatform and LocalPlatform implement Platform. BucketStorage and DiskStorage implement Storage; CloudQueue and MemoryQueue implement JobQueue." caption="The client depends on the three interfaces only."}
classDiagram
  direction LR
  class Platform {
    <<interface>>
    +createStorage() Storage
    +createQueue() JobQueue
  }
  class Storage {
    <<interface>>
  }
  class JobQueue {
    <<interface>>
  }
  Platform <|.. CloudPlatform
  Platform <|.. LocalPlatform
  Storage <|.. BucketStorage
  Storage <|.. DiskStorage
  JobQueue <|.. CloudQueue
  JobQueue <|.. MemoryQueue
  PhotoUploads --> Platform
  PhotoUploads --> Storage
  PhotoUploads --> JobQueue
```

Two design notes. Each create method is a factory method, in the Gang of Four's sense: their book
says abstract factories are often implemented with factory methods. And it adds that a concrete
factory is often a singleton. The advice from the [Singleton](/patterns/singleton-pattern/)
lesson still holds: make one, and pass it in, exactly as `main` does above.

## The cost

A common belief is that this pattern makes every change easy. It makes one kind of change easy, and
the other kind harder.

A **new family** is easy. Another cloud provider is one new class, and nothing else changes. A **new
kind of product** is not. Add `createCache()` to the interface, and every platform class has to add it
before the code compiles again.

```java
public interface Platform {
    Storage createStorage();
    JobQueue createQueue();
    Cache createCache();      // new: every platform must add it
}
```

| | Storage | JobQueue | Cache (new) |
|---|---|---|---|
| CloudPlatform | ✓ | ✓ | must add |
| LocalPlatform | ✓ | ✓ | must add |
| OtherCloudPlatform (new) | one new class | one new class | must add |

The Gang of Four list this as the pattern's main cost: "Supporting new kinds of products is
difficult." Their reason: the abstract factory's interface fixes the set of products, so a new kind
of product means changing the abstract factory and all of its subclasses. (A Java `default` method
on the interface could keep old factories compiling, but then a family can quietly lack a working
piece, which is the mismatch the pattern exists to prevent.)

> **New family: one class. New piece: every class.**

So reach for it when the families grow more often than the pieces.

## In the JDK: Swing's look and feel

The Gang of Four's own example was a user interface toolkit, with several looks for its widgets.
Java's Swing works the same way. You set the look and feel once. Then every component asks the UI
manager for its delegate, the object that draws it.

```java
UIManager.setLookAndFeel(new NimbusLookAndFeel());
JButton save = new JButton("Save");   // drawn by a Nimbus delegate
```

`UIManager.getUI` returns the look and feel's delegate for a component, and `UIDefaults.getUI`
creates it from the class registered for that component's UI class ID. Buttons, scroll bars and menus
all come from the same look and feel, so they always match. Change the look and feel, update the
component tree (`SwingUtilities.updateComponentTreeUI`), and the whole family changes together.
That's why the docs insist on updating every component after a change: a button left with its old
delegate would be a glass king among wooden pawns.

```mermaid {alt="Swing: UIManager.setLookAndFeel picks one look and feel; JButton, JScrollBar and JMenu each ask the UI manager for their delegate, and all delegates come from that same look and feel." caption="One setting, and every widget comes from the same family."}
flowchart TD
  L["setLookAndFeel(Nimbus)"] --> U["UIManager"]
  B["JButton"] -->|getUI| U
  S["JScrollBar"] -->|getUI| U
  M["JMenu"] -->|getUI| U
  U --> F["delegates from one look and feel"]
  class L hl
  class F good
```

## Abstract Factory vs Factory Method

This pattern is often mixed up with [Factory Method](/patterns/factory-method-pattern/).
Factory Method is one creation method that a subclass overrides: the level picks its enemy. Abstract
Factory is a separate object, with one create method for each product, and you pass it in: the
platform makes every piece. In the Factory Method lesson, this was the club's matching kit. And the
two work together: each method on a factory is often a factory method.

```mermaid {alt="Comparison: Factory Method has a Level class with createEnemy, overridden by a subclass such as IceLevel to pick one product. Abstract Factory has a Platform object with createStorage and createQueue, passed into PhotoUploads, making a whole family." caption="One method overridden vs one object passed in."}
flowchart LR
  subgraph FM["Factory Method"]
    direction TB
    L["Level<br/>createEnemy()"] --> I["IceLevel overrides it:<br/>one product"]
  end
  subgraph AF["Abstract Factory"]
    direction TB
    P["Platform<br/>createStorage(), createQueue()"] --> U["passed into PhotoUploads:<br/>a whole family"]
  end
  FM ~~~ AF
  class L,I c1
  class P,U c1
```

| | Factory Method | Abstract Factory |
|---|---|---|
| What it is | one creation method | an object with one method per product |
| Who picks | a subclass of the class that uses it | whoever passes the factory in |
| Makes | one product | a family that must match |

So ask yourself: does one class need to vary one thing it makes? That's Factory Method. Do several
objects have to come from one matching family? That's Abstract Factory.

## When not to use it

- **Only one family**, with no second setup: call `new`, or pass the objects in.
- **The pieces don't have to match**: pass each one in on its own. A factory adds nothing.
- **The kinds of product change every week**: every change touches every factory.

Use it when you have several real families, and the pieces must come from the same one. And start
simple. Two settings that rarely change can wait. When the first mismatch bug shows up, that's your
signal to bring in a factory.

```mermaid {alt="Decision: are there several families? If not, just use new or pass objects in. Must the pieces come from the same family? If not, pass each in separately. Do the kinds of product change often? If yes, expect every factory to change; otherwise use Abstract Factory." caption="Use it when families are real and matching matters."}
flowchart TD
  A{"several families?"} -->|no| N["just new, or pass objects in"]
  A -->|yes| B{"must the pieces match?"}
  B -->|no| E["pass each one in"]
  B -->|yes| C{"product kinds change often?"}
  C -->|yes| W["every change touches every factory"]
  C -->|no| F["Abstract Factory"]
  class N,E muted
  class W warn
  class F good
```

## Recap

- Pieces that must match shouldn't be chosen one by one. One object per family creates every piece.
- The client takes the factory and sees only interfaces. One choice in `main` swaps the whole family.
- A new family is one class; a new kind of piece is every class.
- Swing's look and feel is one you may already use.

```mermaid {alt="Recap chain: pieces must match; one factory per family; the client sees only interfaces; one choice in main swaps the family." caption="Choose the set, not the pieces."}
flowchart LR
  A["pieces must match"] --> B["one factory per family"] --> C["client sees interfaces"] --> D["one choice in main"]
  class B c1
  class D good
```

Checklist:

- Do these objects really have to come from the same family?
- Is there a second family today (a test setup counts), or only in theory?
- Does the client name any concrete product class? It shouldn't.
- Is the family chosen in exactly one place?
- How often do you add a new kind of product, compared with a new family?

> **Choose the set, not the pieces.**

Related lessons: [Factory Method](/patterns/factory-method-pattern/),
[Singleton](/patterns/singleton-pattern/), [Builder](/patterns/builder-pattern/),
[Strategy](/patterns/strategy-pattern/).

## Further reading

- Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, *Design Patterns* (1994): Abstract Factory
  (Intent, Applicability, Consequences, Related Patterns).
- Java SE 21 API: [`UIManager`](https://docs.oracle.com/en/java/javase/21/docs/api/java.desktop/javax/swing/UIManager.html)
  and [`UIDefaults`](https://docs.oracle.com/en/java/javase/21/docs/api/java.desktop/javax/swing/UIDefaults.html).
- refactoring.guru: [Abstract Factory](https://refactoring.guru/design-patterns/abstract-factory).
