Skip to content

Factory Method vs Abstract Factory vs Builder

Difficulty: Intermediate

Key concepts

  • factory method pattern
  • abstract factory pattern
  • builder pattern
  • factory function
  • choosing a pattern
  • The one question each of Factory Method, Abstract Factory, and Builder answers, and why those questions are different even though all three “create objects”.
  • How to choose between them, and when a plain constructor, a struct of options, or simply passing the object in is better than any of them.
  • What each one returns and who owns it, in C++.
  • How they combine in one design without being confused.

Each pattern hides a different decision from the code that needs the object:

  • Factory Method, and its everyday relatives the factory function and the registry, hides which class is created. The caller asks for “an exporter for html” and gets a std::unique_ptr<Exporter>; it never names HtmlExporter.
  • Abstract Factory hides which family several objects come from. A screen asks one WidgetFactory for a button and a checkbox, and they are guaranteed to match: both text, or both HTML, never one of each.
  • Builder hides how one object is assembled and checked. The caller knows exactly what it is making, an HttpRequest, but the request has many optional parts and rules about how they combine, so the parts are collected in steps and checked together in build().

So the first two are about choosing a type the caller must not depend on, and the third is about constructing a value whose type the caller already knows. If neither problem is present, a constructor is the answer.

The creator in each example:

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

make_exporter.hpp
// The one place that knows which class serves which format.
// Takes a format name ("txt", "md", or "html") and returns a brand-new
// exporter for it. The std::unique_ptr in the return type says the caller
// owns the new object: it is deleted when the caller's pointer goes away.
// std::string_view is a read-only view of characters, so a string literal
// or a std::string can be passed without copying it.
// Throws std::invalid_argument, naming the supported formats, for any other.
std::unique_ptr<Exporter> make_exporter(std::string_view format);

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

request_builder.hpp
// Collects a request's parts in any order, then checks them all at once.
// The builder is a separate, changeable object that holds the parts while
// they are being chosen. Only build() turns them into an HttpRequest, and
// only if every rule holds. The builder itself is an ordinary value: it can
// be copied, which lets one partly set-up builder serve as a template.
class RequestBuilder final {
public:
// The parts every request needs are constructor parameters, so they
// cannot be forgotten.
RequestBuilder(Method method, std::string url);
// Each step records one part and returns *this, so steps can be chained.
// `*this` is the builder the step was called on, and the return type
// RequestBuilder& is a reference to it (not a copy), so in
// b.timeout(5s).retries(3) the second step runs on the same builder b.
// header() and query() add one more entry each time they are called;
// body(), json(), timeout(), and retries() replace the earlier value.
RequestBuilder& header(std::string name, std::string value);
RequestBuilder& bearer_token(const std::string& token); // the Authorization header
RequestBuilder& query(std::string name, std::string value);
RequestBuilder& body(std::string content_type, std::string content);
RequestBuilder& json(std::string content); // body("application/json", content)
RequestBuilder& timeout(std::chrono::milliseconds limit);
RequestBuilder& retries(int count);
RequestBuilder& no_redirects();
// Checks every rule, including rules about combinations of parts.
// Throws std::invalid_argument listing every problem it found. The
// builder is unchanged, so a part that a later step replaces (the body,
// the timeout, the retry count) can be corrected and built again.
// `const`: build() only reads the parts, so the builder keeps them.
// It returns the request by value: the caller owns the new HttpRequest.
HttpRequest build() const;
private:
// A body and its content type always travel together, so they are
// one small struct.
struct Body {
std::string content_type;
std::string content;
};
// The parts collected so far, as the steps recorded them. Nothing here
// has been checked yet; that is build()'s job.
Method method_;
std::string url_;
std::vector<Header> headers_; // in the order they were added
std::vector<Header> query_; // name and value pairs, reusing Header
// std::optional: empty until body() or json() is called, so "no body"
// and "an empty body" are different things.
std::optional<Body> body_;
// The defaults for parts no step sets. 30'000 is 30000; the ' only
// groups the digits for the reader. That is 30 seconds.
std::chrono::milliseconds timeout_{30'000};
int max_retries_ = 0;
bool follow_redirects_ = true;
};

class ReportWriter

the creator; abstract; not copyable

Data members

  • virtual std::unique_ptr<Exporter> create_exporter() const = 0; private: the factory method

Member functions

  • std::string write(const Document& document, const std::string& author) const; shared work

class HtmlReportWriter final

a concrete creator; derives from ReportWriter

Data members

  • std::unique_ptr<Exporter> create_exporter() const override; private: returns an HtmlExporter
Factory Method: a base class asks its subclasses which exporter to create

class WidgetFactory

the abstract factory

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: the HTML family; derives from WidgetFactory

Member functions

  • std::unique_ptr<Button> make_button(std::string label) const override; an HtmlButton
  • std::unique_ptr<Checkbox> make_checkbox(std::string label, bool checked) const override; an HtmlCheckbox
Abstract Factory: one function per product kind, one class per family

class RequestBuilder final

the builder; no base class, no virtual functions

Data members

  • Method method_; required: a constructor parameter
  • std::string url_; required: a constructor parameter
  • std::vector<Header> headers_; optional parts, collected step by step
  • std::optional<Body> body_;

Member functions

  • RequestBuilder(Method method, std::string url);
  • RequestBuilder& header(std::string name, std::string value); returns *this
  • RequestBuilder& json(std::string content); returns *this
  • HttpRequest build() const; checks every rule; throws, listing every problem
Builder: one concrete class that collects parts and checks them in build()

The outlines show the difference in C++ terms. The two factories are interfaces with virtual functions that return a std::unique_ptr to a base class: their whole purpose is that the caller does not know the concrete type. The builder is a single final class with no virtual functions, and build() returns an HttpRequest by value: the type is known, and only the assembly is hidden.

Question Factory Method (and factory functions) Abstract Factory Builder
What does it hide? which concrete class which family, for several kinds at once the steps and checks of building one object
What does the caller know? the interface, and a name or a setting the product kinds, never the family the exact type it is making
What comes back? one std::unique_ptr<Exporter> one std::unique_ptr per call, all from one family one HttpRequest, by value
When is the choice made? at each call, from the name, or by which subclass you have once per run (once per loop pass in the example), in widgets_for; every later call follows no type is chosen; the parts are chosen step by step
When are mistakes found? an unknown name throws at the call a mixed family cannot happen through one factory build() throws, listing every broken rule, before the object exists
What is cheap to add? a new format: one class, and one branch or registration where names are mapped a new family; a new kind touches every factory a new optional part: one member, one step, maybe one rule
Needs polymorphism? yes yes no
Choosing how to create an object, starting from what the caller knows
Text description of the diagram

A decision flowchart. The first question: does the caller know the exact class it needs? If yes, ask whether the object has many optional parts, or rules about how they combine. If not, use a constructor, or a struct of options with defaults. If so, use a Builder. If the caller does not know the exact class, because it depends on a name, a setting, or a subclass, ask whether several objects must come from the same family. If yes, use an Abstract Factory. If no, use a factory function, a registry, or the classic Factory Method; the Factory Method page’s “Choosing a form” table chooses between those three.

Diagram source (Mermaid)
flowchart TD
Q1{"Does the caller know<br/>the exact class it needs?"}
Q1 -- "yes" --> Q2{"Many optional parts,<br/>or rules about how<br/>they combine?"}
Q2 -- "no" --> C["Constructor, or a struct<br/>of options with defaults"]
Q2 -- "yes" --> B["Builder"]
Q1 -- "no: it depends on a<br/>name, setting, or subclass" --> Q3{"Must several objects<br/>come from the same family?"}
Q3 -- "yes" --> AF["Abstract Factory"]
Q3 -- "no" --> FM["Factory function, registry,<br/>or classic Factory Method"]
  1. Does the caller know the exact class? This is the question that splits the three. If code writes HttpRequest and means it, there is nothing for a factory to hide. If it writes “whatever exporter matches this file name”, there is.
  2. If it knows the class: is constructing it hard? Hard means many optional parts, parts that accumulate (headers, query parameters), or rules that involve several parts at once, such as “a GET has no body”. Then a builder can collect everything and check it once. If not, use a constructor; for a few optional settings with defaults, a struct and a designated initializer, as get(url, {.timeout = 2s}) does in the Builder example, is clearer than a builder.
  3. If it does not know the class: must several objects match? If a screen needs a button and a checkbox and a mix would be a bug, the choice must be made once, for all of them: Abstract Factory. If each object is chosen on its own, a factory function is enough; the Factory Method page explains when a registry or the classic form is better.
  • A factory returns ownership. make_exporter, the registry’s make, create_exporter, and every WidgetFactory function return a std::unique_ptr, and the caller decides how long the object lives. No creator in these examples keeps a pointer to what it made, so the products do not depend on the creator’s lifetime.
  • An abstract factory is itself an object that someone owns. main owns the chosen WidgetFactory through the std::unique_ptr that widgets_for returns; screen functions borrow it as const WidgetFactory& only during the call. The widgets keep no link back to it, so a screen may outlive the factory. A factory function is just a function, with nothing to own. A registry, by contrast, is an object main owns, and its makers live inside it.
  • A builder is a short-lived value. It is often a temporary in one statement. It stores its parts by value, and build() copies them into the request, so the request does not depend on the builder or on the caller’s strings. Because build() is const, the same builder can build several requests, and after an error it is unchanged, so a problem a later step can correct (a timeout, a retry count, a body) can be corrected and built again.
  • Each function of an abstract factory works like a factory method. HtmlWidgets::make_button is a virtual function that a subclass overrides to choose the concrete class. The difference is who calls it: ReportWriter::write calls its own private create_exporter, while screens call make_button. Abstract Factory groups several such functions so that one choice covers them all.
  • A convenience function, or a factory, can use a builder inside it. The example’s get function builds through RequestBuilder, so every rule is checked in one place, and the caller sees only a simple function. A factory function that reads a configuration file, chooses a class, and configures it through a builder does the same.
  • A builder can choose a class at the end. A builder whose build() returns std::unique_ptr<Exporter>, choosing the class from the parts it collected, is both a builder and a factory. That is fine when both problems are real; name the parts, and document which combinations produce which class.
  • The family can be chosen by a factory function. widgets_for takes a name and returns the right concrete factory: a factory function whose product happens to be an abstract factory.
  • The caller knows the class, and construction is simple. Call the constructor. Use std::make_unique if the object must live on the heap.
  • Only data varies, not behaviour. If “light” and “dark” themes differ only in colours and sizes, a Theme struct with two values is enough. Separate classes, and a factory for them, are for behaviour that differs.
  • Someone else already chose. If the caller is handed the object it needs, it does not need to create anything; see dependency injection. A factory belongs where the decision is made, usually near main, not in every class that uses the result.

Exercise: Pick a creation approach for four scenarios

For each scenario, choose a constructor or struct, a factory function (or registry, or classic Factory Method), an Abstract Factory, a Builder, or no creational code at all. Use the questions above, and say what the caller receives and who owns it.

  1. A logging library reads a setting such as console, file, or syslog at startup and must create the matching sink, which the program then writes to through a LogSink interface. Applications that use the library may add their own sink types.
  2. A database layer supports PostgreSQL and SQLite. Each has its own Connection, Statement, and Transaction classes, and a PostgreSQL statement cannot run on a SQLite connection. The choice is made once, from the configuration file.
  3. A query object has a table name, any number of where conditions that accumulate, an optional order_by, an optional limit, and an optional offset. An offset without a limit is an error.
  4. A charting library offers a light and a dark theme. The two differ only in a background colour, a line colour, and a font size.
Show the explained answer

1. A registry of makers. The caller knows only the LogSink interface and a name (question 1), and each sink is chosen on its own (question 3), so this is a factory. Because applications add their own sink types, a fixed factory function is not enough: a registry lets them add a maker without editing the library, as ExporterRegistry does. The program receives a std::unique_ptr<LogSink> and owns it, usually for the whole run. If the setting is read once and no one adds types, a factory function with an if chain, like make_exporter, is simpler.

2. An Abstract Factory. The classes are chosen from a setting, not known to the caller, and several objects must come from the same family: mixing PostgreSQL and SQLite objects is the bug to prevent (question 3). A Database interface with connect, and a connection that creates its own statements and transactions, is a common way to get the same guarantee, since every later object comes from the connection. In effect the connection is the abstract factory for the rest of the family. Unlike the widgets here, statements and transactions usually refer to their connection, so the connection must outlive them. Either way, the choice is made once, near main, which owns the factory or connection; the code that runs queries borrows it.

3. A Builder. The caller knows the exact type (question 1), but it has accumulating parts and a rule about a combination, offset needs a limit, that can only be checked when everything is known (question 2). The table name is required, so it belongs in the builder’s constructor. build() returns the query by value, and throws for an offset without a limit, so every query that exists is valid.

4. A struct; none of the three patterns. Only data varies, so there are no classes to choose between: a Theme struct with three members, and two values, light_theme and dark_theme, passed to the charts by const reference or copied. If the themes later differ in behaviour, for example the dark theme draws grid lines differently, revisit the choice then.