Abstract Factory gives the client one object, a factory, that creates a whole family of related products: a button, a checkbox and a menu that all share one look, or a connection, a command and a parameter that all belong to one database driver. The client asks the factory for each product through an interface and never names a concrete class. Because every product comes from the same factory, the family is consistent by construction: a dark button can never end up next to a light checkbox. Switching the whole family is one decision, made where the factory is created.
Think of it like
A furniture collection
A furniture shop sells each chair, sofa and table in several collections: Victorian, Modern, Art Deco. When you furnish a room, you pick a collection once and order every piece from it, and the pieces match because they were designed together. You never pick "chair" and then hope its legs suit the table. The collection is the concrete factory, "chair", "sofa" and "table" are the product kinds, and the shop's order form, which lists one line per kind, is the abstract factory interface.
The problem
A settings screen shows a button and a checkbox. The app started with one look, so Screen.build() simply creates the light widgets itself. This is the Before version in the visualizer above.
interface Button {
render(): string;
}
interface Checkbox {
render(): string;
}
class LightButton implements Button {
render(): string {
return "btn-light";
}
}
class LightCheckbox implements Checkbox {
render(): string {
return "chk-light";
}
}
class Screen {
build(): string {
const b = new LightButton(); // concrete class named here
const c = new LightCheckbox(); // and here
return b.render() + " " + c.render();
}
}
new Screen().build(); // "btn-light chk-light"Then users ask for a dark theme. The widgets differ, but they must change together: a dark screen needs a dark button and a dark checkbox. Without a pattern, every place that creates a widget learns about themes:
class Screen {
constructor(private theme: string) {}
build(): string {
const b: Button =
this.theme === "dark" ? new DarkButton() : new LightButton();
const c: Checkbox =
this.theme === "dark" ? new DarkCheckbox() : new LightCheckbox();
return b.render() + " " + c.render();
}
}- The same test repeats at every creation site. Two widgets on one screen means two copies; a real app has dozens of screens and widget kinds, and a third theme adds a branch to every one of them.
- Nothing keeps the family consistent. Each
?:decides on its own. A site that tests a different setting, or one that a developer forgets to update, produces a dark button next to a light checkbox, and the compiler is perfectly happy. Screendepends on every concrete widget. The class that lays out the screen importsLightButton,DarkButton,LightCheckboxandDarkCheckbox, so it changes whenever a theme does.- Themes cannot be added from outside. A plugin or another team that wants a high-contrast theme has to edit
Screenand every other class that creates widgets.
The pattern
Intent (from the Gang of Four book): provide an interface for creating families of related or dependent objects without specifying their concrete classes. The book also calls it Kit.
- Abstract factory (
UiFactory) - An interface with one creation method per product kind:
createButton(),createCheckbox(). Each returns an abstract product type. - Concrete factory (
LightFactory,DarkFactory) - Implements every creation method for one family.
DarkFactoryonly ever makes dark widgets. - Abstract product (
Button,Checkbox) - The interface for one kind of product. The client uses products only through these types.
- Concrete product (
LightButton,DarkCheckbox, ...) - One product kind in one family. There is one class per kind per family.
- Client (
Screen) - Holds a reference to an abstract factory and asks it for products. It never writes
newfor a concrete product and never knows which family it has.
interface UiFactory {
createButton(): Button;
createCheckbox(): Checkbox;
}
class LightFactory implements UiFactory {
createButton(): Button {
return new LightButton();
}
createCheckbox(): Checkbox {
return new LightCheckbox();
}
}
class Screen {
constructor(private ui: UiFactory) {}
build(): string {
const b = this.ui.createButton();
const c = this.ui.createCheckbox();
return b.render() + " " + c.render();
}
}
// The only line that names a family:
new Screen(new LightFactory()).build(); // "btn-light chk-light"Read the class diagram as a grid. Each column is a family: the light column holds LightButton, LightFactory and LightCheckbox, and the factory sits between the two products it creates. Each row is a product kind, with its abstract type in the middle column. Adding a family adds a column; adding a product kind adds a row, and that row runs through every factory (more on that cost below).
What the visualizer shows
- Class diagram: the light family in the left column, the abstract types (
Button,UiFactory,Checkbox) down the middle, andScreenaboveUiFactory, which it holds in itsuifield. WhenScreencallscreateButton(),UiFactorylights violet (it declares the method),LightFactorylights amber (its code runs), and theuiassociation and the implements edge light up. When a widget is created, its dashed «create» arrow lights green. - Objects at runtime:
screen : Screenwithui = ui, the factory objectui : LightFactory, and the two widgets it creates,btn : LightButtonandbox : LightCheckbox. - Sequence of calls:
build()arrives atscreen, which sendscreateButton()and thencreateCheckbox()toui; each call creates a widget and returns it. Only then doesscreencallrender()on each widget.
Press Play in the visualizer at the top of the page, or step with the arrow keys: it really runs the classes in the code panel. The Before / With Abstract Factory toggle switches between the version where build() writes new LightButton() and the pattern. Add dark applies the change request to whichever version is shown: changed classes get a badge, and the Change request panel beside the code counts what each version had to change. On a phone, the three views sit behind a Classes / Objects / Sequence switch.
Walkthrough
- 1
Pick the family once
With With Abstract Factory selected, the client runs
new LightFactory(). This is the only place in the program that names a theme. - 2
Hand the factory to the client
new Screen(ui)stores the factory in the fieldui, typed asUiFactory.Screenis never told which theme it has. - 3
Ask for the first product
screen.build()callsthis.ui.createButton(). The method is declared byUiFactory; the object is aLightFactory, so its code runs and createsbtn, aLightButton, which travels back tobuild()as aButton. - 4
Ask for the second product
this.ui.createCheckbox()goes to the same factory object, which createsbox, aLightCheckbox. Both widgets came from one factory, so they belong to one family. - 5
Use the products through their interfaces
build()callsb.render()andc.render(), which return"btn-light"and"chk-light", and the screen returns"btn-light chk-light". - 6
Add dark (change request)
With Add dark applied, the client creates a
DarkFactoryinstead. The same two lines ofScreennow producebtn : DarkButtonandbox : DarkCheckbox, andbuild()returns"btn-dark chk-dark". No existing class was edited. - 7
Compare with Before + dark
Switch to Before with Add dark still applied:
Screennow has athemefield, and both creation sites testthis.theme === "dark"separately. The run takes the dark branch twice, and nothing but discipline keeps those two tests in agreement.
Before and after
Without the pattern
Screenwritesnew LightButton()andnew LightCheckbox()itself- A new theme adds the same test to every creation site
- Nothing stops a dark button from appearing next to a light checkbox
Screendepends on every concrete widget of every theme- Fewer classes; fine while the app has exactly one look
With Abstract Factory
Screenasks aUiFactoryfor each widget and names no concrete class- A new theme is one factory plus one class per widget, all new
- A family is consistent because it comes from one factory object
- The theme is chosen in one place, where the factory is created
- Costs an extra interface and a factory per family; a new widget kind touches every factory
| Change request: add dark | Before | With Abstract Factory |
|---|---|---|
| Existing classes edited | 1 (Screen) | 0 |
| New classes | 2 (DarkButton, DarkCheckbox) | 3 (DarkFactory, DarkButton, DarkCheckbox) |
| Lines changed in existing classes | 12 (+10 −2) | 0 |
As with Factory Method, the pattern does not save classes: it adds one more (the factory). What it saves is editing the class that uses the widgets. Without it, Screen gains a field, a constructor and a theme test per widget; this toy screen has two widgets, a real app has a test like that at every place it creates one. With it, the new theme is entirely new code, and Screen keeps working unchanged. In both versions the client code changes, because something has to say "use dark".
The weak spot: a new kind of product
Abstract Factory makes adding a family cheap and adding a product kind expensive. A slider for every theme means a new createSlider() on UiFactory, which breaks every class that implements it: LightFactory, DarkFactory and any third-party factory you do not control must all be edited. The Gang of Four list this as the pattern's main liability ("supporting new kinds of products is difficult"). Use the pattern when families change more often than the list of product kinds.
| Change | Without the pattern | With Abstract Factory |
|---|---|---|
| New family (high contrast) | Edit every creation site | Add one factory and one class per product kind; edit nothing |
| New product kind (slider) | Add the classes and a creation site with its theme test | Add the classes and edit the factory interface and every concrete factory |
Variations
| Variation | How it works | Use it when |
|---|---|---|
| Factory as a singleton | An app usually needs one concrete factory per family, so each factory is created once (the GoF book suggests Singleton); in modern code, more often one instance created at startup and passed in | The factory holds no per-use state and one instance per family is enough |
| Creation methods as factory methods | The usual implementation: each createX() is a Factory Method, overridden per family. A base factory may supply defaults that a family overrides selectively | Families share most products and differ in a few |
| Prototype-based factory | One concrete factory class holds a prototype of each product and clones it on request; a family is a set of prototypes, not a subclass (see Prototype) | Many families that differ only in configuration, or families assembled at runtime |
| Registry of factories by name | A map from a family name ("light", "dark", "SqlClient") to a factory instance; configuration picks the name | The family comes from a setting, a file or a plugin |
| DI container chooses the family | The concrete factory is bound to the UiFactory interface in the composition root; classes just ask for a UiFactory (see Dependency Injection) | You already use a container or a composition root |
| Parameterized ("extensible") factory | One method create(kind) instead of one per kind. New kinds need no interface change, but the return type is a common supertype and the client must downcast | Product kinds change often and type safety matters less |
In real code
| Where | Abstract factory | Family it creates |
|---|---|---|
| Java XML (JAXP) | javax.xml.parsers.DocumentBuilderFactory | DocumentBuilderFactory.newInstance() returns the configured parser implementation (chosen by a system property, a config file, ServiceLoader or the platform default), and its newDocumentBuilder() creates that implementation's DocumentBuilder. SAXParserFactory, TransformerFactory and XPathFactory follow the same scheme |
| JDBC | A driver's Connection | createStatement(), prepareStatement() and getMetaData() return the driver's own Statement, PreparedStatement and DatabaseMetaData classes, and a statement's executeQuery() returns the driver's ResultSet. Objects from one connection always belong to one driver |
| .NET ADO.NET | System.Data.Common.DbProviderFactory | CreateConnection(), CreateCommand(), CreateParameter() for one database provider; DbProviderFactories.GetFactory(name) is a registry of factories by provider name |
| GoF book | WidgetFactory (Motif and Presentation Manager look and feel), MazeFactory | The book's motivating example is exactly the theme problem: scroll bars and windows that must match one look and feel |
In application code, look for an interface whose methods all start with create and return interfaces: a cloud SDK wrapper whose AWS and GCP implementations create matching storage, queue and secret clients; a game whose difficulty level creates its enemies, weapons and power-ups; a test setup that swaps a whole family of real services for in-memory fakes.
When to use it, and when not to
Reach for Abstract Factory when
- Several products must be used together and must come from the same family
- The family is chosen once (by configuration, platform or user setting) and used everywhere
- New families are expected, possibly from plugins or other teams
- You want to swap a whole set of collaborators in tests
Keep it simpler when
- There is one family and no sign of a second one (YAGNI)
- Products are independent: nothing breaks if they are mixed, so separate factories or plain constructors do
- Product kinds change more often than families (each new kind edits every factory)
- Only one product varies: that is a Factory Method or a constructor parameter
Abstract Factory vs similar patterns
| Pattern | What it creates | Who decides the class | Key difference |
|---|---|---|---|
| Abstract Factory | A family of related products that must match | The factory object the client was given | One object with a creation method per product kind |
| Factory Method | One product | A subclass, by overriding a method | A single hook on a class that has other work; an abstract factory's methods are usually factory methods |
| Simple factory | One product | A function or static method, from an argument | Not a GoF pattern; a switch in one place. Fine when there are no families to keep consistent |
| Builder | One complex object, step by step | The builder and the steps the client calls | Builder returns the product at the end of a process; Abstract Factory returns each product immediately |
| Prototype | A copy of an existing object | Whichever prototype is cloned | Can implement an abstract factory: a factory that clones configured prototypes needs no subclass per family |
| Bridge | Nothing; it separates an abstraction from its implementation | Whoever wires the two hierarchies | Often used together: an abstract factory can create and configure the right implementation for a bridge (a window and its platform-specific implementation) |
Implementation
The visualizer's scenario as a complete program: a UiFactory interface with light and dark factories, the Button and Checkbox products they create, and a Screen that receives a factory and builds a consistent pair of widgets without naming a concrete class.
from abc import ABC, abstractmethod
class Button(ABC):
@abstractmethod
def render(self) -> str: ...
class Checkbox(ABC):
@abstractmethod
def render(self) -> str: ...
class LightButton(Button):
def render(self) -> str:
return "btn-light"
class LightCheckbox(Checkbox):
def render(self) -> str:
return "chk-light"
class DarkButton(Button):
def render(self) -> str:
return "btn-dark"
class DarkCheckbox(Checkbox):
def render(self) -> str:
return "chk-dark"
class UiFactory(ABC):
"""The abstract factory: one creation method per product kind."""
@abstractmethod
def create_button(self) -> Button: ...
@abstractmethod
def create_checkbox(self) -> Checkbox: ...
class LightFactory(UiFactory):
def create_button(self) -> Button:
return LightButton()
def create_checkbox(self) -> Checkbox:
return LightCheckbox()
class DarkFactory(UiFactory):
def create_button(self) -> Button:
return DarkButton()
def create_checkbox(self) -> Checkbox:
return DarkCheckbox()
class Screen:
"""The client: knows only the interfaces."""
def __init__(self, ui: UiFactory) -> None:
self._ui = ui
def build(self) -> str:
b = self._ui.create_button()
c = self._ui.create_checkbox()
return b.render() + " " + c.render()
def factory_for(theme: str) -> UiFactory:
"""The only place that names a family."""
return DarkFactory() if theme == "dark" else LightFactory()
if __name__ == "__main__":
print(Screen(factory_for("light")).build()) # btn-light chk-light
print(Screen(factory_for("dark")).build()) # btn-dark chk-darkKey takeaways
- Abstract Factory is one object with a creation method per product kind; each concrete factory creates one consistent family.
- The client holds the factory through an interface and never names a concrete product, so the family is chosen in exactly one place.
- Consistency is the point: products from one factory always match, which scattered
if (theme)checks cannot guarantee. - Adding a family adds classes and edits none. In the visualizer's "Add dark" request: 0 existing classes edited with the pattern, versus
Screenedited by 12 lines without it. - Adding a product kind is the weak spot: it changes the factory interface and every concrete factory.
- The creation methods are usually factory methods; the factory itself is often a single shared instance, chosen by configuration or a DI container.
Common pitfalls
- Using it for a single family or for unrelated products: an interface and a factory per family that nothing needs.
- Leaking the family:
instanceof DarkFactorychecks or casts fromButtontoDarkButtonin the client bring back the dependency the pattern removed. - Ignoring the cost of new product kinds: if widgets are added every sprint and themes rarely, every sprint edits every factory.
- Creating products directly somewhere "just this once": one
new LightCheckbox()outside the factory reintroduces mixed families. - Turning the factory into a global singleton that code reaches for, instead of passing it in; it then becomes hard to swap in tests.
Interview tips
- Draw the grid: rows are product kinds, columns are families, the abstract factory is the row of creation methods. Then say "a new column is cheap, a new row touches every factory".
- Expect "Abstract Factory vs Factory Method": an object you pass in (composition) for a family, versus one overridable method (inheritance) for a single product.
- In LLD rounds, use it when the problem has matching sets: themes, cross-platform widgets, database drivers, cloud providers, test doubles. If only one object varies, a simple factory or factory method is enough, and saying so scores points.
Real-world applications
- UI toolkits and design systems with themes or platform look and feel (the GoF book's motivating example).
- Database access layers: a JDBC
Connectionor an ADO.NETDbProviderFactorycreates statements, commands and parameters that belong to one driver. - Pluggable parsers and transformers chosen at runtime, as in Java's JAXP factories.
- Cloud or vendor abstraction layers whose implementations create matching storage, queue and secret clients.
- Test setups that replace a whole family of real services with in-memory fakes.
Test yourself
What problem does Abstract Factory solve that a set of independent factory functions does not?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.