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.
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.
Related objects chosen separately can end up from different worlds.
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 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.
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
ifs. It’s like every player grabbing a piece from whichever set is nearest. Most games look fine,
until one doesn’t.
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.
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.
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.
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.
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
}| 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.
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 delegateUIManager.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.
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.
| 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.
new, or pass the objects in.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.
main swaps the whole family.Checklist:
Choose the set, not the pieces.
Related lessons: Factory Method, Singleton, Builder, Strategy.
UIManager
and
UIDefaults.