Skip to content

Abstract Factory

Difficulty: Intermediate

Key concepts

  • abstract factory pattern
  • product families
  • product kinds
  • concrete factory
  • adding a family vs adding a kind
  • choosing the family once
  • The problem Abstract Factory solves, shown before the pattern is named: objects that only work together, created one at a time by code that can mix them up.
  • How one factory object, chosen once, makes every object a screen needs, so the screen cannot mix families.
  • The pattern’s central trade-off: adding a family is cheap, and adding a kind of product touches every family.
  • How it relates to Factory Method, and when plain data, or one factory function per kind, is the better design.

A small tool configures a fleet of devices. Administrators use it in two ways: in a terminal, over SSH, and in a web browser. Each screen of the tool (settings, login, and more to come) is drawn as text in the terminal and as HTML in the browser.

Requirements:

  1. FR-1 Every screen can be drawn in text mode and in HTML. A screen has buttons and checkboxes.
  2. FR-2 A screen drawn for one UI uses only that UI’s widgets. A text-mode checkbox inside a web page shows raw [ ] characters and cannot be clicked, so a mixed screen is a bug.
  3. FR-3 The UI is chosen once, when the tool starts, from a setting. An unknown UI is an error that names the supported ones.
  4. FR-4 New screens are added often, by different people. Writing a screen must not mean knowing how each UI draws its widgets.

Non-functional requirement:

  • NFR-1 A screen’s contents (which widgets, with which labels and states) can be tested without rendering real text or HTML.
The UI is chosen once; every screen must then use that UI's widgets only
Text description of the diagram

A solid arrow is a flow, and a dashed arrow means “uses”. A start-up setting, text or html, chooses the UI in use. That UI means the text widgets (a button and a checkbox) or the HTML widgets (a button and a checkbox). The screens, settings, login, and more, need a button and checkboxes, and must get them from the UI in use.

Diagram source (Mermaid)
flowchart LR
SETTING["start-up setting<br/>text or html"] -->|"chooses the UI"| UI["the UI in use"]
UI -->|"text"| TEXT["text widgets<br/>button, checkbox"]
UI -->|"html"| HTML["HTML widgets<br/>button, checkbox"]
SCREENS["screens<br/>settings, login, ..."] -.->|"need a button<br/>and checkboxes"| UI

Where Abstract Factory shows up in requirements. Listen for “look and feel”, “platform” (draw with Windows, macOS, or GTK controls), “backend” or “driver” (a database connection, statement, and transaction that must all come from the same driver), and above all “these must match” or “never mix”. The signal is several kinds of object that come in several families, where a mix is a bug. It comes up rarely: most programs have one family, or kinds that never need to match.

The widget classes already exist: an abstract Button and Checkbox, and one concrete class per kind per UI (the code is shown below). Each screen picks the classes itself:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

before.cpp
// Builds the settings screen as text, one widget per line. Every screen
// function receives the UI as a Ui value and picks the concrete classes
// itself, in an if/else with one branch per UI.
std::string settings_screen(Ui ui, const Settings& settings) {
std::string out;
if (ui == Ui::html) {
// HtmlCheckbox{...} creates a temporary widget, .render() draws it,
// and the temporary is destroyed at the end of the statement.
out += HtmlCheckbox{"Send usage reports", settings.usage_reports}.render() + '\n';
out += HtmlCheckbox{"Install updates automatically", settings.auto_update}.render() + '\n';
out += HtmlButton{"Save"}.render() + '\n';
} else {
// The same three widgets, written out again with the Text classes.
out += TextCheckbox{"Send usage reports", settings.usage_reports}.render() + '\n';
out += TextCheckbox{"Install updates automatically", settings.auto_update}.render() + '\n';
out += TextButton{"Save"}.render() + '\n';
}
return out;
}
// The bug: the checkbox line names TextCheckbox whatever `ui` is, so the
// HTML login screen starts with the text line "[ ] Remember me". Nothing
// stops it: the compiler sees a valid class name either way.
std::string login_screen(Ui ui) {
std::string out;
out += TextCheckbox{"Remember me", false}.render() + '\n'; // the same on both, surely?
// Only the button looks at ui. `?:` picks one of two strings: the HTML
// button's when ui is html, the text button's otherwise.
out += (ui == Ui::html ? HtmlButton{"Sign in"}.render() : TextButton{"Sign in"}.render()) + '\n';
return out;
}

settings_screen is right, but only because its author was careful in both branches. login_screen was written later, by someone who assumed a checkbox looks the same everywhere. A test pins down what the HTML login screen does today:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_widgets.cpp
// The HTML login screen contains a text-mode checkbox.
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure
// if the condition is false; LLD_CHECK_EQ(actual, expected) fails, and
// prints both values, unless they are equal. They come from the site's
// small test header, lld_test.hpp. lines_of (split text into lines) and
// all_html (true if every line starts with '<') are small helpers in this
// test file; defaults is a Settings with its default values.
// The test pins down today's behaviour: the HTML login screen's first line
// is the text checkbox, so not every line is HTML, while the HTML settings
// screen, whose author got both branches right, is all HTML.
LLD_TEST(before_the_html_login_screen_mixes_families) {
const std::string login = before::login_screen(before::Ui::html);
const std::vector<std::string> lines = lines_of(login);
LLD_CHECK_EQ(lines.front(), std::string{"[ ] Remember me"});
LLD_CHECK(!all_html(login));
LLD_CHECK(all_html(before::settings_screen(before::Ui::html, defaults)));
}

It fails three requirements:

  • FR-2 fails. The HTML login screen contains a text-mode checkbox. Nothing stops this: every screen names concrete classes, so every screen can name the wrong one.
  • FR-4 fails. Each screen author must know every UI and write one branch per UI. A third UI means editing every screen.
  • NFR-1 fails. The screens construct concrete widgets, so a test can only look at real rendered text or HTML.

And FR-3 is spread out: “which UI are we in?” is asked again in every screen, through a Ui value passed to each one.

Before choosing a pattern, give each piece of knowledge one owner:

Knowledge or job Who should own it Why
what a checkbox is: a label, checked or not the product kind, Checkbox it is the same in every UI, so it is written once
how a checkbox looks in HTML one concrete product, HtmlCheckbox it changes only when the HTML look changes
which family this run uses one object, chosen once at start-up FR-3: decided once; FR-2: everything comes from it, so nothing can be mixed
which widgets a settings screen has, in which order the screen function FR-4: a screen author thinks about content, not looks
the widgets of one screen, once created the Screen, through std::unique_ptr they live exactly as long as the screen

The first two rows sort the members of the product classes:

  • Data members that every family needs (label_, checked_) go in the kind’s base class, Checkbox, with non-virtual functions that use them (label(), checked(), toggle()). Writing them once per family would be the duplicated knowledge this page is trying to remove.
  • The one function whose body depends on the family, render, is virtual, and each concrete product overrides it. The concrete products have no data members of their own.

The third row is the one this page is about. “Which family?” becomes an object, and screens get every widget by asking that object.

Abstract Factory gives the client one object, the factory, with a creation function for each kind of product. Each concrete factory creates the products of one family. A client that gets all its products from one factory gets them all from one family, without naming a family anywhere.

The roles:

  • Abstract products: Button and Checkbox, one per kind.
  • Concrete products: TextButton, TextCheckbox, HtmlButton, HtmlCheckbox, one per kind per family.
  • Abstract factory: WidgetFactory, with make_button and make_checkbox, one function per kind.
  • Concrete factories: TextWidgets and HtmlWidgets, one per family.
  • Client: the screen functions, which take a const WidgetFactory& and use only the abstract products.

interface (abstract class) Widget

anything that can be drawn

Member functions

  • virtual std::string render() const = 0;

class Button

abstract product: a kind; is a Widget

Data members

  • std::string label_; the same in every family

Member functions

  • const std::string& label() const;

class Checkbox

abstract product: a kind; is a Widget

Data members

  • std::string label_;
  • bool checked_;

Member functions

  • const std::string& label() const;
  • bool checked() const;
  • void toggle();

class HtmlCheckbox final

concrete product; also TextCheckbox, TextButton, HtmlButton

Member functions

  • std::string render() const override; the only part that differs by family

interface (abstract class) WidgetFactory

the abstract factory: one function per kind

Member functions

  • virtual std::unique_ptr<Button> make_button(std::string label) const = 0;
  • virtual std::unique_ptr<Checkbox> make_checkbox(std::string label, bool checked) const = 0;

class HtmlWidgets final

a concrete factory: one family; also TextWidgets

Member functions

  • std::unique_ptr<Button> make_button(std::string label) const override; creates an HtmlButton
  • std::unique_ptr<Checkbox> make_checkbox(std::string label, bool checked) const override;

class Screen final

owns the widgets of one screen

Data members

  • std::vector<std::unique_ptr<Widget>> widgets_;

Member functions

  • void add(std::unique_ptr<Widget> widget); throws std::invalid_argument for null
  • std::string render() const;

namespace global

not a real namespace: free functions at file scope

Functions

  • std::unique_ptr<WidgetFactory> widgets_for(std::string_view ui); chooses the family once
  • Screen settings_screen(const WidgetFactory& widgets, const Settings& settings); a client
  • Screen login_screen(const WidgetFactory& widgets); a client
Kinds, families, the factory interface, and the client functions
The client uses only the factory interface and the product kinds; each concrete factory creates its own family
Text description of the diagram

A solid arrow means “creates”, a dashed arrow means “uses”, and a thick arrow means “implements”. The client, settings_screen, asks the WidgetFactory interface for widgets and uses them only as the product kinds Button and Checkbox. TextWidgets and HtmlWidgets implement WidgetFactory. TextWidgets creates TextButton and TextCheckbox; HtmlWidgets creates HtmlButton and HtmlCheckbox. Both families implement the product kinds Button and Checkbox.

Diagram source (Mermaid)
flowchart TB
CLIENT["settings_screen<br/>client"] -.->|"asks for widgets"| WF["WidgetFactory<br/>abstract factory"]
CLIENT -.->|"uses"| KINDS["Button, Checkbox<br/>product kinds"]
TW["TextWidgets"] ==>|implements| WF
HW["HtmlWidgets"] ==>|implements| WF
TW -->|creates| TP["TextButton,<br/>TextCheckbox"]
HW -->|creates| HP["HtmlButton,<br/>HtmlCheckbox"]
TP ==>|implement| KINDS
HP ==>|implement| KINDS

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

widgets.hpp
// Anything that can be drawn on a screen. This is an interface: it has a
// virtual destructor and one pure virtual function (`= 0`), so no one can
// create a plain Widget, only an object of a class derived from it.
// render() returns the widget as text: a line of console text or of HTML,
// depending on which family the real object belongs to.
class Widget {
public:
// Virtual, so that deleting a widget through a Widget pointer (which
// is what std::unique_ptr<Widget> does) runs the real class's
// destructor too, not only Widget's.
virtual ~Widget() = default;
Widget(const Widget&) = delete; // owned through unique_ptr, never copied
Widget& operator=(const Widget&) = delete;
// `= 0` makes this pure virtual: every concrete widget must say how
// it looks. `const`: drawing a widget does not change it.
virtual std::string render() const = 0;
protected:
// Protected: only a derived class's constructor can call it, so the
// only way to get a Widget is to make a concrete one.
Widget() = default;
};
// The product kinds. Each holds what every family needs; a family
// decides only how it looks.
// A Button is a label and nothing else. It does not override render(),
// so it is still abstract: a real button is a TextButton or HtmlButton.
class Button : public Widget {
public:
const std::string& label() const { return label_; }
protected:
// The label is taken by value and then moved into label_: a caller
// passing a temporary string pays for no copy at all. `explicit`
// stops a plain string from turning into a Button by accident.
explicit Button(std::string label) : label_{std::move(label)} {}
private:
std::string label_;
};
// A Checkbox is a label plus an on/off state. The state belongs to the
// kind, not the family, so toggle() works the same for every family.
class Checkbox : public Widget {
public:
const std::string& label() const { return label_; }
bool checked() const { return checked_; }
// Flips the state: on becomes off, off becomes on.
void toggle() { checked_ = !checked_; }
protected:
Checkbox(std::string label, bool checked) : label_{std::move(label)}, checked_{checked} {}
private:
std::string label_;
bool checked_;
};
  • Widget is not copyable. Widgets are created by a factory and owned through std::unique_ptr, so nothing needs to copy one, and deleting the copy operations rules out slicing one widget into another through a base reference.
  • The kinds hold the shared data. Button and Checkbox are still abstract (they do not override render), and their constructors are protected: only a family’s class can create one.

Each family is a set of small classes that only decide the look:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

families.hpp
// The text-mode family, for the console over SSH.
// TextButton draws as "[ label ]", for example "[ Save ]". `final` means
// no class may derive from it: it is a finished, concrete widget.
class TextButton final : public Button {
public:
// Hands the label on to Button's constructor, which stores it. Being
// derived from Button is what lets it call that protected constructor.
explicit TextButton(std::string label) : Button{std::move(label)} {}
// `override` asks the compiler to check that this really replaces
// Widget::render; a typo in the signature becomes an error.
std::string render() const override;
};
// TextCheckbox draws as "[x] label" when checked, "[ ] label" when not.
class TextCheckbox final : public Checkbox {
public:
TextCheckbox(std::string label, bool checked) : Checkbox{std::move(label), checked} {}
std::string render() const override;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

families.hpp
// The web family, for the browser.
// HtmlButton draws as "<button>label</button>", with the label escaped:
// characters such as & and < are written as &amp; and &lt; so that they
// show as text instead of being read as HTML.
class HtmlButton final : public Button {
public:
explicit HtmlButton(std::string label) : Button{std::move(label)} {}
std::string render() const override;
};
// HtmlCheckbox draws as a checkbox input inside a label element, with
// the word "checked" added when it is on, and the label escaped too.
class HtmlCheckbox final : public Checkbox {
public:
HtmlCheckbox(std::string label, bool checked) : Checkbox{std::move(label), checked} {}
std::string render() const override;
};

HtmlButton and HtmlCheckbox escape their labels, so a label such as Save & <exit> cannot break the page.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

widget_factory.hpp
// The abstract factory: one function per product kind. A screen that
// gets all its widgets from one factory gets them all from one family.
// Each make_ function creates a new widget and hands it to the caller as
// a std::unique_ptr: the caller becomes its only owner, and it is deleted
// automatically when that owner lets it go. The factory keeps nothing.
class WidgetFactory {
public:
virtual ~WidgetFactory() = default;
// Pure virtual (`= 0`): each family's factory decides which concrete
// class to create. The return type is the kind (Button, Checkbox), so
// the caller can use a Checkbox's toggle() without knowing the family.
// `const`: making a widget does not change the factory.
virtual std::unique_ptr<Button> make_button(std::string label) const = 0;
virtual std::unique_ptr<Checkbox> make_checkbox(std::string label, bool checked) const = 0;
protected:
// Protected, so only derived classes use them. A TextWidgets can still
// be copied as a whole, but code holding two WidgetFactory references
// cannot assign one to the other and copy only the base part (slicing).
WidgetFactory() = default;
WidgetFactory(const WidgetFactory&) = default;
WidgetFactory& operator=(const WidgetFactory&) = default;
};
// One concrete factory per family.
// TextWidgets makes only text-mode widgets: TextButton and TextCheckbox.
class TextWidgets final : public WidgetFactory {
public:
std::unique_ptr<Button> make_button(std::string label) const override;
std::unique_ptr<Checkbox> make_checkbox(std::string label, bool checked) const override;
};
// HtmlWidgets makes only web widgets: HtmlButton and HtmlCheckbox.
class HtmlWidgets final : public WidgetFactory {
public:
std::unique_ptr<Button> make_button(std::string label) const override;
std::unique_ptr<Checkbox> make_checkbox(std::string label, bool checked) const override;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

widget_factory.cpp
// Each function creates one widget of its own family and nothing else.
// std::make_unique<TextButton>(...) creates a TextButton on the heap and
// returns a std::unique_ptr<TextButton> that owns it. The return type
// says std::unique_ptr<Button>, and a unique_ptr to a derived class
// converts to one to its base class, so ownership passes to the caller
// unchanged: the object is still a TextButton. std::move(label) hands the
// string on instead of copying it (the parameter is not used afterwards).
std::unique_ptr<Button> TextWidgets::make_button(std::string label) const {
return std::make_unique<TextButton>(std::move(label));
}
std::unique_ptr<Checkbox> TextWidgets::make_checkbox(std::string label, bool checked) const {
return std::make_unique<TextCheckbox>(std::move(label), checked);
}
// The HTML family: the same two functions, the same shape, but each
// names an Html class. Each factory is paired with its widget classes
// here, once, so a screen never picks a widget class itself.
std::unique_ptr<Button> HtmlWidgets::make_button(std::string label) const {
return std::make_unique<HtmlButton>(std::move(label));
}
std::unique_ptr<Checkbox> HtmlWidgets::make_checkbox(std::string label, bool checked) const {
return std::make_unique<HtmlCheckbox>(std::move(label), checked);
}

Some details matter in C++:

  • Each creation function returns the kind, not Widget. make_checkbox returns std::unique_ptr<Checkbox>, so the caller can call toggle() without a cast. Returning std::unique_ptr<Widget> from one make(kind) function would throw that away.
  • The caller owns each product. As with any factory, the result is a std::unique_ptr, and the factory keeps nothing.
  • The factories have no state, so their functions are const, and one factory can serve every screen for the whole run.
  • Each creation function is a factory method: a virtual function that a derived class overrides to choose the concrete type. (In the classic Factory Method, the base class calls it from its own work; here the client calls it.) An abstract factory is a set of them that must agree on a family.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

widget_factory.hpp
// Choose the family once, at startup. Throws std::invalid_argument for
// an unknown name.
// ui is "text" or "html". The result is a new factory owned by the
// caller, returned as the abstract WidgetFactory, so the caller does not
// learn which concrete factory it got. std::string_view is a read-only
// view of the caller's characters, so a string literal is not copied.
std::unique_ptr<WidgetFactory> widgets_for(std::string_view ui);

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

widget_factory.cpp
// Compares the name with each supported UI and creates the matching
// factory. Each `return` leaves at once, so reaching the throw means no
// name matched. Comparing a std::string_view with "text" compares the
// characters, not pointers.
std::unique_ptr<WidgetFactory> widgets_for(std::string_view ui) {
if (ui == "text") {
return std::make_unique<TextWidgets>();
}
if (ui == "html") {
return std::make_unique<HtmlWidgets>();
}
// std::string{ui} copies the view into a real string so it can be
// joined with +. The message lists what is supported, for example
// "unknown ui 'voice'; supported: html, text".
throw std::invalid_argument{"unknown ui '" + std::string{ui} + "'; supported: html, text"};
}

This is the one place in the program that names the families (FR-3). It is a plain factory function whose product happens to be a factory.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

screens.hpp
// A screen owns its widgets and keeps no link to the factory that made them.
class Screen final {
public:
// Takes ownership of one widget: the std::unique_ptr is taken by value,
// so the caller must hand theirs over (a temporary, or std::move).
void add(std::unique_ptr<Widget> widget); // throws std::invalid_argument for null
// Renders the widgets in the order they were added, each followed by
// a newline. An empty screen renders as an empty string.
std::string render() const; // one widget per line
// A unique_ptr cannot be copied, so code that tries to copy a Screen
// does not compile; a Screen can be moved, which is how the screen
// functions below can return one by value.
private:
// Each element owns one widget. The vector stores Widget pointers, so
// it can hold buttons and checkboxes of any family side by side. When
// the screen is destroyed, the vector deletes every widget.
std::vector<std::unique_ptr<Widget>> widgets_;
};
// The client code: it knows product kinds, never families.
// Each builds one screen from whatever factory it is given, borrowed for
// the call only (`const WidgetFactory&`), and returns the screen by value.
Screen settings_screen(const WidgetFactory& widgets, const Settings& settings);
Screen login_screen(const WidgetFactory& widgets);

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

screens.cpp
// Asks the factory for two checkboxes and a button, in the order they
// appear on the screen. Only the kinds are named here (make_checkbox,
// make_button); which family's class is created is decided by the
// factory that was passed in. The checkbox states come from settings.
Screen settings_screen(const WidgetFactory& widgets, const Settings& settings) {
Screen screen;
// make_checkbox returns a std::unique_ptr<Checkbox>. It is a temporary,
// so it is moved straight into add's std::unique_ptr<Widget> parameter
// (a Checkbox is a Widget): no std::move is needed here.
screen.add(widgets.make_checkbox("Send usage reports", settings.usage_reports));
screen.add(widgets.make_checkbox("Install updates automatically", settings.auto_update));
screen.add(widgets.make_button("Save"));
// The screen, with the widgets it now owns, goes back to the caller:
// moved out, or built in the caller's place by the compiler directly.
return screen;
}
// The same shape as settings_screen: no `if` on the UI, so this screen
// cannot mix families the way the before-version's login screen did.
Screen login_screen(const WidgetFactory& widgets) {
Screen screen;
screen.add(widgets.make_checkbox("Remember me", false));
screen.add(widgets.make_button("Sign in"));
return screen;
}
How this code works: settings_screen with the HTML factory

Follow one call, settings_screen(*widgets, settings), where widgets_for("html") made the factory and settings has usage_reports false and auto_update true, as in main.

  1. The factory is borrowed. The parameter widgets is a const WidgetFactory& that refers to the HtmlWidgets object owned by main. settings_screen does not know, or need to know, that it is the HTML family.
  2. A virtual call picks the family. widgets.make_checkbox(...) is a call to a virtual function, so at run time it goes to the version in the object’s real class: HtmlWidgets::make_checkbox. With a TextWidgets object, the same line would run TextWidgets::make_checkbox.
  3. One widget is created, and its ownership passes along. std::make_unique<HtmlCheckbox> creates the checkbox and returns a std::unique_ptr<HtmlCheckbox>. It becomes a std::unique_ptr<Checkbox> as the function returns, then a std::unique_ptr<Widget> as it is passed to add. These are three views of the same object, and at each step exactly one pointer owns it.
  4. The screen takes it. add checks the pointer is not empty, then push_back(std::move(widget)) moves it into the screen’s vector. From now on the screen owns the widget, and destroying the screen deletes it. Because Widget has a virtual destructor, that deletion runs HtmlCheckbox’s destructor, even though the vector only knows Widget.

The three requests, in order:

Call, with the values from settings filled in Function that runs Object created Stored at
make_checkbox("Send usage reports", false) HtmlWidgets::make_checkbox an unchecked HtmlCheckbox widgets_[0]
make_checkbox("Install updates automatically", true) HtmlWidgets::make_checkbox a checked HtmlCheckbox widgets_[1]
make_button("Save") HtmlWidgets::make_button an HtmlButton widgets_[2]

When main calls render() on the returned screen, Screen::render calls each widget’s own render in that order, which gives the three HTML lines under == html == in the output below, ending with <button>Save</button>. The factory is not involved any more: the screen holds everything it needs.

The screen functions now say only what is on the screen. They take the factory as a const WidgetFactory&: they borrow it for one call and keep no pointer to it. There is no if on the UI and no concrete class name: screens.cpp does not even include families.hpp. Getting every widget from the factory is now the easy path, and one a reviewer can check by looking at the includes, so the login screen no longer mixes families (FR-2), and a new screen needs no UI knowledge at all (FR-4). The concrete classes are still public, so nothing forces this. To turn the rule into a build error, keep families.hpp private to the widget library, so screen code cannot include it.

Object Owner Lives
the factory for this run main, through the std::unique_ptr from widgets_for the whole run, or one loop pass in the example
a widget the Screen it was added to, through std::unique_ptr<Widget> as long as that screen
a Screen whoever called the screen function; returned by value until the caller lets it go
the factory, in a screen function borrowed as const WidgetFactory& only during the call

The widgets do not point back to the factory that created them, so a screen may outlive its factory. That is a choice worth keeping: if a widget kept a reference to its factory (for example, to create child widgets later), the factory would have to outlive every screen.

Drawing the HTML settings screen: the family is chosen once, and every widget comes from it
Text description of the diagram

main calls widgets_for with html, which creates an HtmlWidgets factory. main calls settings_screen with that factory and the settings. settings_screen asks the factory to make a checkbox, “Send usage reports”, unchecked; the factory creates an HtmlCheckbox and returns a unique_ptr to it as a Checkbox. settings_screen asks for a second checkbox and a “Save” button the same way. It returns a Screen that owns the three widgets. main renders the screen, which calls render on each widget; the HtmlCheckbox returns its HTML.

Diagram source (Mermaid)
sequenceDiagram
participant M as main
participant S as settings_screen
participant F as HtmlWidgets
participant C as HtmlCheckbox
M->>F: widgets_for(html) creates it
M->>S: settings_screen(factory, settings)
S->>F: make_checkbox(Send usage reports, false)
F->>C: creates
F-->>S: unique_ptr to a Checkbox
S->>F: make_checkbox(...) and make_button(Save)
F-->>S: a Checkbox and a Button
S-->>M: a Screen that owns the three widgets
M->>C: render, through Screen render
C-->>M: the HTML for the checkbox

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// Draws both screens in each UI, then shows that an unknown UI is refused.
int main() {
// Designated initializers (C++20): each member is set by name.
const Settings settings{.usage_reports = false, .auto_update = true};
// Runs the loop body twice, with ui = "text" and then ui = "html".
for (const char* ui : {"text", "html"}) {
// The one place a family is chosen. `widgets` owns the factory, and
// the factory is destroyed at the end of each pass of the loop.
const std::unique_ptr<WidgetFactory> widgets = widgets_for(ui);
std::cout << "== " << ui << " ==\n";
// *widgets is the factory itself, lent to the screen function as a
// const WidgetFactory&. The returned Screen is a temporary: it is
// rendered, then destroyed with its widgets at the end of the
// statement. The screens do not need the factory to outlive them.
std::cout << settings_screen(*widgets, settings).render();
std::cout << login_screen(*widgets).render();
}
// "voice" is not a supported UI, so widgets_for throws before it
// returns anything. std::invalid_argument is a kind of std::exception,
// so this catch receives it, and what() is the message it was given.
try {
widgets_for("voice");
} catch (const std::exception& error) {
std::cout << "error: " << error.what() << '\n';
}
}
Expected output
== text ==
[ ] Send usage reports
[x] Install updates automatically
[ Save ]
[ ] Remember me
[ Sign in ]
== html ==
<label><input type="checkbox"> Send usage reports</label>
<label><input type="checkbox" checked> Install updates automatically</label>
<button>Save</button>
<label><input type="checkbox"> Remember me</label>
<button>Sign in</button>
error: unknown ui 'voice'; supported: html, text

Read the output against the requirements:

  • Each screen is drawn in both UIs from the same screen function (FR-1).
  • Every HTML line is HTML, including the login screen’s “Remember me” checkbox, which the before-version drew as text (FR-2).
  • voice is refused with an error that lists html, text (FR-3).
  • And, as the code above shows, the screen functions contain no UI names (FR-4).

For NFR-1, a test supplies a fake family. Its widgets render as plain descriptions such as button:Save, so a test sees what a screen asked for, without any real text or HTML:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_widgets.cpp
// A fake family, so a test can check a screen without real rendering.
// Each fake widget renders as a plain description of what it is, such as
// "button:Save" or "checkbox:on:Beta", which is easy to compare in a test.
// They derive from the real kinds, Button and Checkbox, so a screen
// cannot tell them from real widgets.
class FakeButton final : public Button {
public:
explicit FakeButton(std::string label) : Button{std::move(label)} {}
std::string render() const override { return "button:" + label(); }
};
class FakeCheckbox final : public Checkbox {
public:
FakeCheckbox(std::string label, bool checked) : Checkbox{std::move(label), checked} {}
std::string render() const override {
return std::string{"checkbox:"} + (checked() ? "on:" : "off:") + label();
}
};
// The fake factory: the same two functions as TextWidgets and HtmlWidgets,
// creating fake widgets. Any screen function accepts it, because it takes
// any WidgetFactory.
class FakeWidgets final : public WidgetFactory {
public:
std::unique_ptr<Button> make_button(std::string label) const override {
return std::make_unique<FakeButton>(std::move(label));
}
std::unique_ptr<Checkbox> make_checkbox(std::string label, bool checked) const override {
return std::make_unique<FakeCheckbox>(std::move(label), checked);
}
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_widgets.cpp
// static_assert checks a fact while the code compiles: if it is false, the
// build fails. std::is_abstract_v<T> is true when T has a pure virtual
// function left, so no object of T itself can be created.
static_assert(std::is_abstract_v<WidgetFactory>);
static_assert(std::is_abstract_v<Button> && std::is_abstract_v<Checkbox>);
static_assert(!std::is_copy_constructible_v<HtmlButton>); // widgets are owned, not copied
// Draws both screens with the HTML factory and checks that every line is
// HTML; then draws the login screen with the text factory and checks that
// every line starts with '[', as "[ ] Remember me" and "[ Sign in ]" do.
LLD_TEST(every_widget_from_one_factory_belongs_to_that_family) {
const HtmlWidgets html;
LLD_CHECK(all_html(settings_screen(html, defaults).render()));
LLD_CHECK(all_html(login_screen(html).render()));
const TextWidgets text;
for (const std::string& line : lines_of(login_screen(text).render())) {
LLD_CHECK(starts_with(line, "["));
}
}
// With the fake factory, the rendered screen is a list of what the screen
// asked for: which kinds, in which order, with which labels and states.
// usage_reports is true and auto_update false, so the first checkbox is
// on and the second off. Proves NFR-1: no real text or HTML is involved.
LLD_TEST(a_screen_asks_for_kinds_and_the_factory_decides_the_look) {
const FakeWidgets fake;
const Settings settings{.usage_reports = true, .auto_update = false};
LLD_CHECK_EQ(settings_screen(fake, settings).render(),
std::string{"checkbox:on:Send usage reports\n"
"checkbox:off:Install updates automatically\n"
"button:Save\n"});
}
// The same request to each factory gives each family's own look.
// make_button returns a std::unique_ptr; ->render() calls through it. The
// temporary pointer deletes its widget at the end of the statement.
LLD_TEST(each_family_renders_its_widgets_its_own_way) {
const TextWidgets text;
const HtmlWidgets html;
LLD_CHECK_EQ(text.make_button("Save")->render(), std::string{"[ Save ]"});
LLD_CHECK_EQ(html.make_button("Save")->render(), std::string{"<button>Save</button>"});
LLD_CHECK_EQ(text.make_checkbox("Dark mode", true)->render(), std::string{"[x] Dark mode"});
LLD_CHECK_EQ(html.make_checkbox("Dark mode", false)->render(),
std::string{"<label><input type=\"checkbox\"> Dark mode</label>"});
}
// toggle() belongs to the Checkbox kind, so it can be called on the
// std::unique_ptr<Checkbox> without knowing the family. HtmlWidgets{} is a
// temporary factory that is gone after the first line; the checkbox lives
// on, because a widget keeps no link to the factory that made it.
LLD_TEST(products_keep_their_kind_behaviour_whatever_the_family) {
const std::unique_ptr<Checkbox> box = HtmlWidgets{}.make_checkbox("Beta", false);
box->toggle();
LLD_CHECK(box->checked());
LLD_CHECK_EQ(box->render(), std::string{"<label><input type=\"checkbox\" checked> Beta</label>"});
}
// & and < > in a label are written as &amp; &lt; &gt;, so the label shows
// as text in a browser instead of breaking the page.
LLD_TEST(html_widgets_escape_their_labels) {
LLD_CHECK_EQ(HtmlWidgets{}.make_button("Save & <exit>")->render(),
std::string{"<button>Save &amp; &lt;exit&gt;</button>"});
}
// widgets_for turns a name into a factory, and refuses an unknown name.
// LLD_CHECK_THROWS(expression, type) fails unless the expression throws an
// exception of that type.
LLD_TEST(the_family_is_chosen_once_by_name) {
LLD_CHECK_EQ(widgets_for("text")->make_button("OK")->render(), std::string{"[ OK ]"});
LLD_CHECK_EQ(widgets_for("html")->make_button("OK")->render(),
std::string{"<button>OK</button>"});
LLD_CHECK_THROWS(widgets_for("voice"), std::invalid_argument);
}
// nullptr converts to an empty std::unique_ptr<Widget>, which add refuses
// with std::invalid_argument. The screen is left empty, so it renders as
// the empty string.
LLD_TEST(a_screen_refuses_a_null_widget) {
Screen screen;
LLD_CHECK_THROWS(screen.add(nullptr), std::invalid_argument);
LLD_CHECK_EQ(screen.render(), std::string{});
}

The central trade-off: a new family or a new kind

Section titled “The central trade-off: a new family or a new kind”

Lay the products out as a table, with kinds as rows and families as columns. Abstract Factory makes one direction cheap and the other expensive:

kind / family text HTML a new family (Markdown)
button TextButton HtmlButton one new class (MarkdownButton)
checkbox TextCheckbox HtmlCheckbox one new class (MarkdownCheckbox)
a new kind (field) one new class (TextField) one new class (HtmlField)

On top of the table: a new family also needs one new factory, and a new kind needs one new function in every factory.

  • A new family is cheap. Add one concrete product per kind, one concrete factory, and one branch in widgets_for (and its error message). No screen, no interface, and no other family changes. This direction is open for extension: the only existing code that changes is the chooser.
  • A new kind is expensive. Add the kind’s class, one concrete product per family, and one function to WidgetFactory, which every concrete factory must then implement: the text and HTML factories, the tests’ fake, and any factory written outside your code. The interface everyone depends on has changed.

The expensive direction has one good property in C++: the new function is pure virtual, so a factory that does not implement it is abstract, and the compiler refuses to create one. The error appears where an object of that factory is created (in widgets_for, or in a test), not where the class is defined; Clang also warns at the definition, because an abstract class marked final can never be used. You cannot ship a family that silently lacks the new kind. Do not soften this with a default implementation that throws or returns null; that moves the error to run time, in the family nobody tested.

So choose Abstract Factory when you expect families to be added more often than kinds. If the kinds keep growing and the families are fixed, the pattern makes every change touch every family.

Use Abstract Factory when:

  • several kinds of object must come from the same family, and a mix is a bug;
  • the family is chosen at run time, once, and much code must follow that choice without knowing it;
  • families are added more often than kinds;
  • clients should be testable with a fake family.
  • Many small classes: one per kind per family, plus a factory per family. Two kinds and two families is already four concrete products and two concrete factories, plus the factory interface.
  • A new kind touches everything, as described above.
  • An indirection. To see what a screen draws, a reader must know which factory it was given. The family chooser is the one place to look.
  • Families that differ only in data. A “light” and a “dark” theme that differ only in colours are one family with two Palette values (a struct of colours passed to the widgets), not two families of classes. Use classes only when the behaviour (here, the whole rendering) differs.
  • An abstract factory with one kind. A factory interface with only make_button has no family to keep consistent. A factory function, or a maker such as std::function<std::unique_ptr<Button>()> passed in, does the same job with less code.
  • One make(kind) function returning std::unique_ptr<Widget>. It looks smaller, but every caller must cast the result back to Checkbox to use it, and a family that cannot make some kind fails at run time.
  • A global “current factory”. Making the factory a Singleton or a global variable lets any code reach it, hides which code depends on the UI, and makes it hard for a test to pass in a fake. Create it in main and pass it in.
  • Branching on the family anyway. A screen that checks dynamic_cast<const HtmlWidgets*>(&widgets) to do something special has undone the pattern. If one UI really needs different content, give that UI its own screen function instead of a cast inside a shared one.
  • “Add a third UI, for generated help pages in Markdown.” A new family: cheap. See the exercise.
  • “Screens need a text field.” A new kind: every family and every factory changes. See the exercise.
  • “High-contrast mode for the web UI.” If only colours and sizes change, it is data for the HTML family, not a new family.
  • “Each logged-in user picks their own UI.” Create one factory per session instead of one per run, and pass it to that session’s screens. Nothing in the screens changes, because they only borrow a factory.

Exercise: Add a product, then add a family

  1. Screens need a field: a label and an editable text value. Add a Field kind. List every class and function that changes, and write the new code for the text and HTML families.
  2. The team wants a third UI, Markdown, for generated help pages: a button is **Save**, a checkbox is - [x] label, and a field is label: `value` . List every class and function that changes.
  3. Compare your two lists. Which change did the pattern make cheap, and why does that matter when deciding whether to use it?
  4. A teammate proposes a LightWidgets and a DarkWidgets factory, whose widgets differ only in colour. What would you suggest instead?
Show the explained answer

1. The kind holds the data every family needs:

// The new kind: a label and an editable text value. Like Button and
// Checkbox, it holds the data every family needs, does not override
// render() (so it stays abstract), and has a protected constructor.
class Field : public Widget {
public:
const std::string& label() const { return label_; }
const std::string& value() const { return value_; }
// Takes the new value by value and moves it in, as the constructors do.
void set_value(std::string value) { value_ = std::move(value); }
protected:
Field(std::string label, std::string value)
: label_{std::move(label)}, value_{std::move(value)} {}
private:
std::string label_;
std::string value_;
};
// The text family's field draws as "label: [value]".
class TextField final : public Field {
public:
TextField(std::string label, std::string value) : Field{std::move(label), std::move(value)} {}
std::string render() const override { return label() + ": [" + value() + "]"; }
};
// The HTML family's field: a text input inside a label element.
class HtmlField final : public Field {
public:
HtmlField(std::string label, std::string value) : Field{std::move(label), std::move(value)} {}
std::string render() const override; // in families.cpp, next to escaped()
};
// In families.cpp, because escaped() is private to that file. Both the
// label and the value are escaped; the value sits inside value="...", so
// a quote in it must become &quot;, which escaped() does.
std::string HtmlField::render() const {
return "<label>" + escaped(label()) + " <input type=\"text\" value=\"" + escaped(value()) +
"\"></label>";
}
// In WidgetFactory: one more pure virtual function, so every concrete
// factory that does not add make_field becomes abstract and cannot be
// created.
virtual std::unique_ptr<Field> make_field(std::string label, std::string value) const = 0;
// In TextWidgets (and the same in HtmlWidgets, with HtmlField):
std::unique_ptr<Field> TextWidgets::make_field(std::string label, std::string value) const {
return std::make_unique<TextField>(std::move(label), std::move(value));
}

What changes: the new Field class; TextField and HtmlField; WidgetFactory; every concrete factory, which here means TextWidgets, HtmlWidgets, and the tests’ FakeWidgets (with a FakeField); and any factory another team wrote. A factory that was not updated is abstract, so the compiler stops at the line that creates one (const FakeWidgets fake;, or the std::make_unique in widgets_for). The screens that want a field change too, which is the point of the request.

2. A Markdown button, checkbox, and field class; one MarkdownWidgets factory with three functions; one more if in widgets_for, and markdown in its error message. That is all: no screen, no kind, no other family, and no existing unit test changes (the expected output of the example changes only because the error message now lists markdown), and every existing screen can be drawn in Markdown at once.

3. The new family was cheap, and the new kind touched every family. Abstract Factory fits when families are added more often than kinds. If this tool expects a new kind of widget every month and a new UI every few years, the pattern makes the common change the expensive one; it may still be worth it if mixing families is a real risk, but the cost should be a known choice.

4. One family, with the colours as data: a Palette struct (for example, background, text, and accent colours) passed to the HTML widgets or the factory when it is created. Light and dark are then two Palette values. Two factory classes would duplicate every widget class to change a few strings, and a third theme would mean a third copy.

  • Factory Method: each creation function of an abstract factory is a factory method, and the family chooser, widgets_for, is a factory function. See Factory Method.
  • Bridge: this design still needs one class per kind per family. Bridge separates the two hierarchies, so the kinds and the ways of drawing can vary without a class for every pair. Its cost is one drawing interface whose operations every kind can be expressed in, so a new kind is cheap only while those operations are enough. The two are often combined, with a factory creating the right drawing implementation. See Bridge.
  • Singleton: a concrete factory is often made a singleton. It does not need to be; create one and pass it in. See Singleton for why to avoid it.
  • Builder: assembles one object from many parts, where a factory chooses which class to create. See Builder, and Factory Method vs Abstract Factory vs Builder.
  • Abstract Factory fits when several kinds of object come in several families, and mixing families is a bug.
  • The client gets every product from one factory object, chosen once, so it cannot mix families and never names one.
  • In C++, each creation function returns std::unique_ptr to the kind (Button, Checkbox), and the caller owns the result.
  • A new family is cheap; a new kind changes every factory. Choose the pattern when families grow more often than kinds.
  • Families that differ only in data are one family with different values. A single kind needs only a factory function or a maker.