Abstract Factory

November 26, 20268 minutes

A 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.

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.

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. 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.
Two settings, each fine on its own, that don't match.

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.

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). 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).
Pick the set, and the pieces follow.

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.

// 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 \ queuelocalcloud
localmatchesthe bug from the start
cloudmismatchmatches

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 ifs. It’s like every player grabbing a piece from whichever set is nearest. Most games look fine, until one doesn’t.

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. 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.
Pieces chosen one by one: every setting is a chance to mismatch.

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.

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.

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.

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:

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:

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 ifs didn’t disappear. They shrank to one, in main, where the program is put together.

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. 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.
One choice in main; every piece follows it.

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.

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. 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.
The client depends on the three interfaces only.

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 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.

public interface Platform {
    Storage createStorage();
    JobQueue createQueue();
    Cache createCache();      // new: every platform must add it
}
StorageJobQueueCache (new)
CloudPlatform✓✓must add
LocalPlatform✓✓must add
OtherCloudPlatform (new)one new classone new classmust 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.

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.

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. 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.
One setting, and every widget comes from the same family.

Abstract Factory vs Factory Method

This pattern is often mixed up with Factory Method. 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.

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. 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.
One method overridden vs one object passed in.
Factory MethodAbstract Factory
What it isone creation methodan object with one method per product
Who picksa subclass of the class that uses itwhoever passes the factory in
Makesone producta 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.

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. 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.
Use it when families are real and matching matters.

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.
Recap chain: pieces must match; one factory per family; the client sees only interfaces; one choice in main swaps the family. Recap chain: pieces must match; one factory per family; the client sees only interfaces; one choice in main swaps the family.
Choose the set, not the pieces.

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, Singleton, Builder, Strategy.

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 and UIDefaults.
  • refactoring.guru: Abstract Factory.