AlgoViz

Abstract factory

medium 50 min

The 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

0:00 / 4:44

Abstract factory

1:03Reel

More reels

One idea each, a minute or less.

Play all in Bytesized Learning

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

  1. 1994

    The book Design Patterns describes Abstract Factory, also known as Kit, among its creational patterns.

  2. 1996

    Java 1.0 ships java.awt.Toolkit, an abstract class whose subclasses bind components to the native toolkit of a platform.

  3. 2005

    .NET Framework 2.0 adds DbProviderFactory: one factory per database provider for connections, commands and parameters.

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

Step 1 of 3

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.

Noor furnishes the reading room
Such an empty room!WISHESa chaira tablea shelf

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.

Python
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)
Run it. One place asks for sea, the other asks for anything that is not forest. A third style slips between them.
Edit and run it in your browser

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

Room- style: String+ addChair(): if style+ addTable(): if style+ addShelf(): if style

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

The smell: the same condition decides the class of several objects that must fit together.

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

askscreatesRoom- chair: Chair- table: Table+ describe()«interface»FurnitureFactory+ createChair(): Chair+ createTable(): Table«interface»Chair+ sitOn()+ style()«interface»Table+ putOn(item)+ style()

1/3What the client sees

Room sees a factory and the kinds of product. All of them are interfaces.

usesdepends onimplements

Upper row: what the client may know. Lower row: one family. Each further family is one more lower row.

Same calls, another family

The room sends the same four messages whatever the family is. Only the object behind F changes.

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

FamilyButtonCheckboxDialogLook
WindowsWindowsButtonWindowsCheckboxWindowsDialogStraight edges
macOSMacButtonMacCheckboxMacSheetRounded, slides out of the window
LinuxLinuxButtonLinuxCheckboxLinuxDialogFollows the desktop theme
Three rows and three columns: 9 product classes, 3 factories, 4 interfaces. That is 16 types, so the matching rule must be worth it.

How the number of types grows

f⋅k⏟products+f⏟factories+k+1⏟interfaces\underbrace{f \cdot k}_{\text{products}} + \underbrace{f}_{\text{factories}} + \underbrace{k + 1}_{\text{interfaces}}
f families, k kinds. 3 and 3 give 9 + 3 + 4 = 16. A new family adds k + 1 new types and edits none. A new kind adds f + 1 new types and edits all f + 1 factory types.

Which way does your grid grow?

Open for families, not open for kinds. Say both halves. See Open/closed.

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.

Java
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();    }}
The operating system is asked once, at the start. The rest of the program contains no if about it.

From setting to widgets

The decision is on the left, its effects are on the right, and only one object passes between them.

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 Theme record 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
DarkThemeFactory and LightThemeFactory create 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

PatternCreatesFocusExample
Abstract factoryA family of products through one objectThe products fit togetherWidgets of one platform
Factory methodOne product through one overridable methodA subclass decides which classA document editor creates its document
BuilderOne product in stepsMany options, checked at the endAn HTTP request
PrototypeA copy of an exampleObjects that are costly to set upA shape palette
SingletonThe only object of a classHow many there areOften the factory object itself
A concrete factory often uses factory methods inside. The difference is the question they answer: which class, or which matching set.

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?

Three questions. Most candidates for the pattern leave at the second or third.

Where the grid appears

AreaFamiliesKinds
GUI toolkitsWindows, macOS, LinuxButton, checkbox, dialog, menu
ThemesDark, light, a customer's brandWidgets with different behaviour
Furniture storeModern, Victorian, forest, seaChair, table, sofa, shelf
Database driversMySQL, PostgreSQL, OracleConnection, command, transaction
DocumentsPDF, HTML, WordHeading, paragraph, table, image
Game renderingDirectX, Metal, Vulkan, or 2D and 3DBuffer, texture, shader, pipeline
Cloud servicesAWS, Azure, Google CloudStorage, compute, messaging
Mobile appsiOS, AndroidNative views
PluginsOne per pluginPanel, settings, command
BrowsersOne per engineNodes of a page
ChartsSVG, canvasAxis, line, label
SecurityOne per providerKey, signer, verifier
Possible uses, not claims about products. Named libraries, checked on their own pages, are in Real world.

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.

Sources