Abstract factory
medium 50 minThe Abstract factory creates families of objects that must fit together, without the client knowing a single concrete class.
Video lesson · Chapter 1 of 6
Make a prediction
Abstract factory
1:03Reel
More reels
One idea each, a minute or less.
Factory method vs abstract factory
0:32Reel
Theory
Read or listen first. About 2 min.
What it is
The Abstract factory is a creational design pattern. An interface declares one creation method for each kind of product. Each class that implements it makes the products of one family.
The client holds one factory through the interface. It asks for a button, then for a checkbox, and gets two objects that were made for each other. It never learns their classes.
Picture a grid. Columns are kinds of product, rows are families. A concrete factory is one row.
Why it exists
When related objects are created in many places, each place decides again which variant to use. Sooner or later two places disagree, and a mixed set appears that compiles, starts, and is wrong.
The pattern moves the decision to one place and one moment. Afterwards matching is the easy path: everything that comes from one factory belongs together.
It also cuts a dependency. The client can be compiled, tested and reused without Windows widgets or a real database.
A short history
1994
The book Design Patterns describes Abstract Factory, also known as Kit, among its creational patterns.
1996
Java 1.0 ships java.awt.Toolkit, an abstract class whose subclasses bind components to the native toolkit of a platform.
2005
.NET Framework 2.0 adds DbProviderFactory: one factory per database provider for connections, commands and parameters.
2011
Java 7 adds java.nio.file.FileSystem, documented as the factory for paths, path matchers and other objects of one file system.
Words to know
- Family
- Products that are made to be used together, for example all Mac widgets.
- Kind
- A type of product, such as button or table. One column of the grid.
- Abstract factory
- The interface with one creation method per kind.
- Concrete factory
- A class that creates one family.
- Abstract product
- The interface of one kind of product.
- Concrete product
- The product of one kind in one family.
- Client
- Code that uses the factory and the products through interfaces only.
- Kit
- Another name for the pattern.
- Owner check
- A test at run time that two objects come from the same factory.
- Capability interface
- A small extra interface that some factories offer and others do not.
- Session
- A factory whose family is one open transaction.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Choose a family. Once, near the start
Understand it
Start here
Things that must match
Some objects only make sense together. A chair that clips into a table. A button and a dialog of the same operating system. A database command and the connection that will run it. The danger is not creating one wrong object. The danger is creating two right objects that do not belong together.
One list, many workshops. Adding a workshop is easy. Adding a line to the list is work for all of them.
Five parts
Abstract factory
One creation method per kind of product:
GUIFactory,FurnitureFactory,ThemeFactory.Concrete factory
Makes the products of one family:
WindowsFactory,ForestFactory.Abstract product
An interface for one kind of product:
Button,Checkbox,Chair.Concrete product
One product of one family:
WindowsButton,ForestChair.Client
Uses only the abstract types:
Application,Room. It receives its factory, it does not choose one.
Why
The mixing problem
Two checks of the same setting, written by two people in two places. Both look right.
class ForestChair: clip = "leaf"class SeaChair: clip = "wave"class ForestTable: clip = "leaf"class SeaTable: clip = "wave"def make_chair(style): return SeaChair() if style == "sea" else ForestChair()def make_table(style): # somebody else, some months later return ForestTable() if style == "forest" else SeaTable()for style in ["forest", "sea", "desert"]: chair, table = make_chair(style), make_table(style) fits = "fits" if chair.clip == table.clip else "DOES NOT FIT" print(style, "->", chair.clip, "chair,", table.clip, "table:", fits)sea, the other asks for anything that is not forest. A third style slips between them.For forest and sea the program is right, so every test that existed passed. The rule "the chair and the table must match" stood nowhere. It was true by luck.
The design that hurts
1/3One class that decides everything
Room asks about the style three times. The three answers must agree, and nothing makes them agree.
depends on
Created by one family
- Style is chosen once
- The client knows interfaces only
- One factory gives one family
- Tests pass a factory of fakes
Created one by one
- Style is checked in many places
- The client knows every concrete class
- A mixed set compiles and runs
- Tests need the real widgets or a real database
The idea
Put the matching rule into one object
Collect the creation of everything that must match in one class. Give the client an object of that class. Now the rule has a home: the class ForestFactory is the sentence "forest chairs go with forest tables".
The furniture families
1/3What the client sees
Room sees a factory and the kinds of product. All of them are interfaces.
usesdepends onimplements
Same calls, another family
The grid
Kinds across, families down
Draw a grid before you draw classes. A column is a kind of product. A row is a family. A concrete factory is a row. If you can not fill the grid, or if the rows do not have to match, you do not have this problem.
Three families of widgets
| Family | Button | Checkbox | Dialog | Look |
|---|---|---|---|---|
| Windows | WindowsButton | WindowsCheckbox | WindowsDialog | Straight edges |
| macOS | MacButton | MacCheckbox | MacSheet | Rounded, slides out of the window |
| Linux | LinuxButton | LinuxCheckbox | LinuxDialog | Follows the desktop theme |
How the number of types grows
Which way does your grid grow?
Choosing the row
One decision, made once
Somebody must name a concrete factory. Keep that in one place near the start of the program. Everything after it receives the factory and never asks again.
final class Main { static GUIFactory factoryFor(String osName) { if (osName.startsWith("Windows")) return new WindowsFactory(); if (osName.startsWith("Mac")) return new MacFactory(); if (osName.startsWith("Linux")) return new LinuxFactory(); throw new IllegalArgumentException("no widgets for " + osName); } public static void main(String[] args) { GUIFactory factory = factoryFor(System.getProperty("os.name")); Application app = new Application(factory); // depends on interfaces only app.createUI(); }}if about it.From setting to widgets
The app must support a dark and a light theme. Where does the choice live?
BreaksAn if in every widget
- How
- Each constructor reads the setting and picks colours.
- Limit
- The question is copied. A half repainted window appears when the setting changes between two calls.
- Choose when
- Never for things that must match.
WorksOne palette object
- How
- A
Themerecord with colours and sizes is passed to ordinary widgets. - Limit
- Only data can differ, not behaviour.
- Choose when
- Dark and light normally need nothing more. Choose this first.
StrongA factory per family
- How
DarkThemeFactoryandLightThemeFactorycreate widgets with their own classes.- Limit
- Many small classes.
- Choose when
- The families differ in behaviour, for example a Mac sheet and a Windows dialog.
Neighbours
The other ways to create
| Pattern | Creates | Focus | Example |
|---|---|---|---|
| Abstract factory | A family of products through one object | The products fit together | Widgets of one platform |
| Factory method | One product through one overridable method | A subclass decides which class | A document editor creates its document |
| Builder | One product in steps | Many options, checked at the end | An HTTP request |
| Prototype | A copy of an example | Objects that are costly to set up | A shape palette |
| Singleton | The only object of a class | How many there are | Often the factory object itself |
Choosing
When to use it and when not
Use it when
- Products of different families must not be mixed
- The client must not depend on how products are made
- Whole families are added or switched
- Several platforms, drivers or file formats must behave alike
- A test needs a complete fake world
Leave it when
- There is one kind of product
- The products do not have to match
- Families differ only in data, such as colours
- New kinds of product appear all the time
- One family exists and a second is only a guess (YAGNI)
Do I need it?
Where the grid appears
| Area | Families | Kinds |
|---|---|---|
| GUI toolkits | Windows, macOS, Linux | Button, checkbox, dialog, menu |
| Themes | Dark, light, a customer's brand | Widgets with different behaviour |
| Furniture store | Modern, Victorian, forest, sea | Chair, table, sofa, shelf |
| Database drivers | MySQL, PostgreSQL, Oracle | Connection, command, transaction |
| Documents | PDF, HTML, Word | Heading, paragraph, table, image |
| Game rendering | DirectX, Metal, Vulkan, or 2D and 3D | Buffer, texture, shader, pipeline |
| Cloud services | AWS, Azure, Google Cloud | Storage, compute, messaging |
| Mobile apps | iOS, Android | Native views |
| Plugins | One per plugin | Panel, settings, command |
| Browsers | One per engine | Nodes of a page |
| Charts | SVG, canvas | Axis, line, label |
| Security | One per provider | Key, signer, verifier |
What you gain, what you pay
The family is kept
One factory object makes one family. The matching rule is in a class that you can read and test.
Classes stay hidden
Concrete names appear in their factory and in the one place that picks it.
Families are exchanged
Pass another factory and the whole set changes at once.
New kinds are hard
One more method in the interface breaks every factory, also those of other teams.
Many types
Reading one click means opening several files. Below two real families this is a loss.
The common part only
The client can use only what all families share. A trick of one platform needs a way out.
Summary
The whole topic in one minute.
Draw the grid: kinds across, families down. A concrete factory is a row. The client sees the interfaces only, and the factory is chosen once, near the start.
Adding a row touches nothing. Adding a column touches every factory, so use defaults or capability interfaces when others implement yours.
The plain types do not forbid mixing. Use one factory per client, an owner check or a family in the type. Products that share a resource make the factory a scope that closes them. And if only values differ, a record is enough.
- Abstract factory keeps a set of objects matching by creating them in one place.
- Columns are kinds, rows are families, and a concrete factory is a row.
- The client knows the factory interface and the product interfaces, nothing else.
- The concrete factory is chosen once, near the start, and passed in.
- A new family is new code. A new kind edits every factory.
- The types alone do not stop somebody with two factories from mixing. One factory per client does.