Factory Method
What you will learn on this page
Section titled “What you will learn on this page”- The problem factories solve, shown before any pattern is named: the same “which class do I create?” decision, copied into several places, drifting apart.
- Three ways to put that decision in one place: a creation function, a registry of makers, and the classic Factory Method, a virtual function that derived classes override.
- Why a factory in modern C++ returns
std::unique_ptr, and who owns what afterwards. - How to choose among the three, and when you need no factory at all.
The problem
Section titled “The problem”A notes app exports a document (a title, then sections of paragraphs) to a file. Two parts of the app export: a command-line tool, and a “Save as” dialog in the desktop app.
Requirements:
- FR-1 Export a document as plain text (
txt), Markdown (md), or HTML (html). - FR-2 The format is chosen while the app runs: by name on the
command line (
export plan.doc md), and from the file name in the “Save as” dialog (plan.md). Both must accept exactly the same formats and produce the same file for the same format. - FR-3 An unknown format is an error that names the supported formats. The app never silently saves in a different format.
- FR-4 Another team writes extra formats as plugins, compiled separately. Adding one must not mean editing the export code.
Non-functional requirement:
- NFR-1 Code that uses an exporter must not depend on the concrete exporter classes, so tests can give it a fake.
Text description of the diagram
A solid arrow is a flow or “creates”. The command-line tool passes a format name, such as md, and the Save as dialog passes a file name, such as plan.md, to one place that chooses the exporter for a format. A plugin adds extra formats to that same place. That place creates an exporter: txt, md, html, or a plugin’s format.
Diagram source (Mermaid)
flowchart LR
CLI["command-line tool<br/>format name"] -->|"md"| CHOOSE["choose the exporter<br/>for a format"]
DIALOG["Save as dialog<br/>file name"] -->|"plan.md"| CHOOSE
PLUGIN["plugin<br/>extra formats"] -->|"adds formats"| CHOOSE
CHOOSE -->|creates| EXP["an exporter<br/>txt, md, html, ..."]Where factories show up in requirements. Listen for “depending
on the setting (file type, input, user’s choice), create a…”,
“support more formats (drivers, providers) later”, and
“plugins”. In code, the signal is the same if/switch on a name
followed by new or std::make_unique, copied wherever objects of
that family are made. Factories come up sometimes: wherever a
running program picks one class out of a family.
The straightforward solution
Section titled “The straightforward solution”The exporters already exist, one class per format, behind one interface:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The product: turns a document into the contents of one kind of file.// Every format (text, Markdown, HTML, ...) is a class derived from this// one, so code that only needs "some exporter" can hold an Exporter and// call render without knowing which format it has.class Exporter {public: // Virtual, so that deleting a derived exporter through a // std::unique_ptr<Exporter> runs the derived class's destructor too. virtual ~Exporter() = default; // The one job: the whole file's contents, as text, for `document`. // `= 0` makes it pure virtual: Exporter has no render of its own, so // it is abstract (no plain Exporter object can exist) and every // concrete format must write one. `const`: rendering changes nothing, // so one exporter can render any number of documents. virtual std::string render(const Document& document) const = 0;
protected: // Protected: only derived classes can use these. Outside code cannot // create a bare Exporter, or copy or assign one through an Exporter&, // which would copy only the base part of a derived object (slicing). // The derived classes can still be copied as themselves. Exporter() = default; Exporter(const Exporter&) = default; // protected: no copying through a base reference Exporter& operator=(const Exporter&) = default;};Each part of the app that exports picks the class itself:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The command-line tool's export: `format` is the word the user typed// ("txt", "md", or "html"). Picks the exporter class itself, renders,// and returns the text. Throws std::invalid_argument for any other word,// with a message that does not say which formats would have worked.std::string export_for_command_line(const Document& document, const std::string& format) { // Starts empty (a null pointer); one branch below fills it with a new // exporter. std::unique_ptr owns that object and deletes it when this // function ends. std::make_unique<T>() creates a T and returns it in a // unique_ptr; assigning a unique_ptr<TextExporter> to a // unique_ptr<Exporter> is allowed because TextExporter is an Exporter. std::unique_ptr<Exporter> exporter; if (format == "txt") { exporter = std::make_unique<TextExporter>(); } else if (format == "md") { exporter = std::make_unique<MarkdownExporter>(); } else if (format == "html") { // added last month, here only exporter = std::make_unique<HtmlExporter>(); } else { throw std::invalid_argument{"unknown format: " + format}; } // `->` calls render on the object the pointer owns. It is a virtual // call, so the chosen class's render runs. return exporter->render(document);}
// The "Save as" dialog's export: the format comes from the end of the// file name. The same choice as above, written a second time, and the two// copies already disagree: this one knows "markdown" but not "html", and// it never throws, because anything it does not recognise becomes text.std::string export_for_save_dialog(const Document& document, const std::string& file_name) { // rfind finds the LAST '.', so "a.tar.gz" gives "gz". It returns // std::string::npos ("not found") when there is no dot; the `?:` then // uses an empty extension. substr(dot + 1) is everything after the dot. const auto dot = file_name.rfind('.'); const std::string extension = dot == std::string::npos ? "" : file_name.substr(dot + 1); std::unique_ptr<Exporter> exporter; if (extension == "md" || extension == "markdown") { exporter = std::make_unique<MarkdownExporter>(); } else { exporter = std::make_unique<TextExporter>(); // anything else is saved as text } return exporter->render(document);}Using the exporter is fine. Choosing it is the problem: the choice is written twice, and the two copies have already drifted. A test pins down what they do today:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false, and LLD_CHECK_THROWS(expression, type) fails// unless the expression throws that type of exception. They come from the// site's small test header, lld_test.hpp.//// `sample` (defined earlier in this file) is a document titled "Plan"// with one section, "Goals", holding one paragraph, "Ship it.".// starts_with(text, prefix) is a small helper: true if `text` begins// with `prefix`. Only the start of each output is checked, because the// start is enough to tell the three formats apart.//// Two copies of the same choice, and they have drifted apart. This test// records today's behaviour, wrong parts included: the same request,// "HTML", gives HTML on the command line and plain text in the dialog.LLD_TEST(before_the_two_places_that_create_exporters_disagree) { const std::string from_command_line = before::export_for_command_line(sample, "html"); const std::string from_dialog = before::export_for_save_dialog(sample, "plan.html"); LLD_CHECK(starts_with(from_command_line, "<h1>Plan</h1>")); // Text output: the title, then a line of '=' as long as the title. LLD_CHECK(starts_with(from_dialog, "Plan\n====")); // saved as plain text // And the other way round: the dialog knows "markdown", the command // line does not. LLD_CHECK(starts_with(before::export_for_save_dialog(sample, "plan.markdown"), "# Plan")); LLD_CHECK_THROWS(before::export_for_command_line(sample, "markdown"), std::invalid_argument);}It fails every requirement except FR-1:
- FR-2 fails. HTML was added to the command line only, so the
dialog saves
plan.htmlas plain text. The dialog acceptsmarkdown, and the command line refuses it. - FR-3 fails. The dialog’s
elsesaves any unknown file name as text, silently, and the command line’s error does not name the supported formats. - FR-4 fails. A plugin format means editing both functions, and remembering every other place that might choose an exporter.
- NFR-1 fails. Each function constructs concrete exporters itself, so a test has no way to give it a fake.
Step 1: sort the data and the functions
Section titled “Step 1: sort the data and the functions”The before-version has four kinds of knowledge mixed into two functions. Give each one a single owner:
| Knowledge or job | Who should own it | Why |
|---|---|---|
| how to turn a document into Markdown (and so on) | each exporter class | it changes only when that format changes |
| which class serves which format name | one creation point | FR-2 says both callers must agree; one copy cannot drift |
| which part of a file name names the format | one small function, extension_of |
the dialog needs it, and its edge cases deserve their own tests |
| the exporter object, once created | the caller, as std::unique_ptr |
the caller decides how long it lives; the factory keeps nothing |
The second row is the one this page is about. Notice what the creation point does not own: rendering (that stays in the exporters, so the factory does not grow with every formatting rule) and the created object (the factory hands it over and forgets it).
The pattern, and its relatives
Section titled “The pattern, and its relatives”Separating “which concrete class to create” from “using the object” can be done in three ways in C++, and the names are often mixed up:
- A factory function (often called a “simple factory”): a free
function that takes a name or a setting and returns a
std::unique_ptrto the base class. It is not one of the classic patterns, but it is the form you will use most. - A factory registry: a table from names to makers, here
std::functionobjects that each create one kind. Code outside the table can add rows to it at run time. - The classic Factory Method: a base class does its work with an object it does not create itself. It calls a virtual function, the factory method, and each derived class overrides it to create the right concrete type.
The roles are the same in all three:
- Product:
Exporter, the interface the created object is used through. - Concrete products:
TextExporter,MarkdownExporter,HtmlExporter, and any plugin format. - Creator: whatever makes the choice:
make_exporter, theExporterRegistry, or, in the classic form,ReportWriter, whose subclasses are the concrete creators. - Client: code that asks the creator for a product and uses it
through the interface, here
export_as.
interface (abstract class) Exporter
the product
Member functions
virtual std::string render(const Document& document) const = 0;
class TextExporter final
a concrete product; also MarkdownExporter, HtmlExporter
Member functions
std::string render(const Document& document) const override;
class ExporterRegistry final
a creator: names to makers
Data members
std::map<std::string, Maker, std::less<>> makers_;Maker = std::function<std::unique_ptr<Exporter>()>
Member functions
void add(std::string format, Maker make);std::unique_ptr<Exporter> make(std::string_view format) const;caller owns the resultstd::vector<std::string> formats() const;
class ReportWriter
a creator: the classic form
Member functions
std::string write(const Document& document, const std::string& author) const;virtual std::unique_ptr<Exporter> create_exporter() const = 0;private; the factory method
namespace global
not a real namespace: free functions at file scope
Functions
std::unique_ptr<Exporter> make_exporter(std::string_view format);a creator: free functionstd::string export_as(const ExporterRegistry& registry, const Document& document, std::string_view format);the client
Text description of the diagram
A solid arrow means “creates”, a dashed arrow means “uses”, and a thick arrow means “implements”. The client, export_as, asks the ExporterRegistry (a creator) for a product, and uses only the Exporter interface’s render. Three creators can each create an HtmlExporter: the registry through a maker, the make_exporter function, and HtmlReportWriter in its create_exporter. TextExporter, MarkdownExporter, and HtmlExporter implement Exporter. (The other creators create the other exporters the same way; one is drawn to keep the diagram small.)
Diagram source (Mermaid)
flowchart TB
CLIENT["export_as<br/>client"] -.->|"asks for a product"| REG["ExporterRegistry<br/>creator"]
CLIENT -.->|"uses render"| EXP["Exporter<br/>product interface"]
REG -->|"creates, via a maker"| HTML["HtmlExporter"]
FN["make_exporter<br/>creator"] -->|creates| HTML
WRITER["HtmlReportWriter<br/>creator"] -->|"creates, in<br/>create_exporter"| HTML
TEXT["TextExporter"] ==>|implements| EXP
MD["MarkdownExporter"] ==>|implements| EXP
HTML ==>|implements| EXPThe C++ implementation
Section titled “The C++ implementation”The product
Section titled “The product”The Exporter interface above has one function, render, which is
const: an exporter has no state of its own, so the same object could
render many documents. Its copy operations are protected, so code
holding an Exporter& cannot assign one exporter over another and
slice it; the concrete classes are final and copy normally.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The three concrete products, one class per format. Each overrides// render and nothing else. `final` means no class can derive from them;// `override` asks the compiler to check that render really matches the// virtual function in Exporter (see the idiom reference on interfaces).// They have no data members, so creating one costs almost nothing.
// Plain text: the title underlined with '=' signs, then each heading and// its paragraphs on their own lines.class TextExporter final : public Exporter {public: std::string render(const Document& document) const override;};
// Markdown: "# title", "## heading" for each section, and a blank line// before each paragraph.class MarkdownExporter final : public Exporter {public: std::string render(const Document& document) const override;};
// HTML: an <h1> for the title, an <h2> per heading, and a paragraph// element per paragraph, one per line. The characters// & < > and " in the text are escaped (& becomes &, and so on), so the// document's text cannot be mistaken for HTML tags.class HtmlExporter final : public Exporter {public: std::string render(const Document& document) const override;};Form 1: a factory function
Section titled “Form 1: a factory function”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 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).
// One `if` per format, each returning at once. A string_view compares// with a string literal character by character, so `format == "txt"`// means "is the text exactly txt?" (case matters: "TXT" is not "txt").std::unique_ptr<Exporter> make_exporter(std::string_view format) { if (format == "txt") { // Creates a TextExporter; the returned unique_ptr<TextExporter> // converts to the unique_ptr<Exporter> the function promises. return std::make_unique<TextExporter>(); } if (format == "md") { return std::make_unique<MarkdownExporter>(); } if (format == "html") { return std::make_unique<HtmlExporter>(); } // Only reached if no `if` matched. std::string{format} copies the view // into a real string, so `+` can join it with the other text. The list // of supported formats is typed by hand here: a second copy of the // `if` chain above, which must be kept in step with it. throw std::invalid_argument{"unknown format '" + std::string{format} + "'; supported: html, md, txt"};}This alone fixes FR-2 and FR-3: both callers call make_exporter, so
they cannot disagree, and the last line refuses anything unknown, by
name. Three details matter in C++:
- It returns
std::unique_ptr<Exporter>. The caller owns the new object, and the type says so. A rawExporter*would leave the reader guessing who deletes it. It cannot return anExporterby value:Exporteris abstract, and even a non-abstract base returned by value would slice off the derived part. And it does not returnstd::shared_ptr: a caller who needs shared ownership can convert aunique_ptrinto one, but the other direction is impossible. - It takes
std::string_view, so callers can pass a string literal, astd::string, or part of a file name without copying. - It is a function, not a class. It has no state, so an
ExporterFactoryclass with one static function would add only a name.
The limit: FR-4 still fails. A plugin format means editing this function.
Form 2: a registry of makers
Section titled “Form 2: a registry of makers”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Formats are added at run time, so code that is not part of this file// (a plugin, a test) can add one without editing it.// The idea: instead of an `if` per format, keep a table with one row per// format: the format's name, and a small function (a "maker") that creates// a new exporter of that format each time it is called.class ExporterRegistry final {public: // A Maker is "any callable that takes nothing and returns a // std::unique_ptr<Exporter>". std::function can hold a lambda, a plain // function, or anything else that can be called that way, so each row // of the table can create a different class. An empty std::function // (for example one made from nullptr) holds nothing to call. using Maker = std::function<std::unique_ptr<Exporter>()>;
// Throws std::invalid_argument for an empty name, an empty maker, or // a name that is already registered. void add(std::string format, Maker make);
// A new exporter, owned by the caller. Throws std::invalid_argument, // naming the registered formats, for an unknown one or a maker that // returns null. std::unique_ptr<Exporter> make(std::string_view format) const;
std::vector<std::string> formats() const; // sorted
private: // The table: format name -> maker. A std::map keeps its keys sorted // and holds each key at most once. The third template argument, // std::less<>, is the comparison; this "transparent" form lets find() // compare a std::string_view with the std::string keys directly, so a // lookup does not have to build a std::string first. std::map<std::string, Maker, std::less<>> makers_; // less<>: look up by string_view};
// A registry with the three formats every build of the app has: "html",// "md", and "txt". Returned by value: the caller gets its own registry and// may add more formats to it.ExporterRegistry standard_exporters();VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Adds one row to the table. Both parameters are taken by value, so the// registry gets its own copies, and std::move then hands them to the map// without copying again. All the checks come first: a refused add leaves// the table unchanged.void ExporterRegistry::add(std::string format, Maker make) { // `!make` is true when the std::function is empty (it has nothing to // call), as when a caller passes nullptr. if (format.empty() || !make) { throw std::invalid_argument{"a format needs a name and a maker"}; } // contains (C++20) asks "is this key in the map already?". Replacing // an existing format silently would hide a mistake, so it is refused. if (makers_.contains(format)) { throw std::invalid_argument{"format '" + format + "' is already registered"}; } // emplace builds the new map entry from the two values in place. // After the moves, `format` and `make` are not used again. makers_.emplace(std::move(format), std::move(make));}
// Looks the format up, runs its maker, and returns the new exporter.// Throws std::invalid_argument for an unknown format (the message lists// the known ones) and for a maker that returns a null pointer.std::unique_ptr<Exporter> ExporterRegistry::make(std::string_view format) const { // find returns an iterator: a pointer-like position in the map. It // points at the matching entry, or equals makers_.end() if there is none. const auto found = makers_.find(format); if (found == makers_.end()) { // Build "html, md, txt" from the table itself: put ", " before // every name except the first (when `known` is still empty). std::string known; for (const std::string& name : formats()) { known += (known.empty() ? "" : ", ") + name; } throw std::invalid_argument{"unknown format '" + std::string{format} + "'; supported: " + known}; } // A map entry is a pair: found->first is the format's name and // found->second is its Maker. The `()` after it calls the maker, which // creates a new exporter each time. std::unique_ptr<Exporter> exporter = found->second(); // A maker could return an empty unique_ptr. Catch it here, naming the // format, rather than let the caller crash later on exporter->render. if (!exporter) { throw std::invalid_argument{"the maker for '" + found->first + "' returned nothing"}; } // Ownership moves out to the caller; the registry keeps no pointer. return exporter;}
// The registered names, in alphabetical order.std::vector<std::string> ExporterRegistry::formats() const { std::vector<std::string> names; // Each `entry` is a name-and-maker pair; only the name is wanted. for (const auto& entry : makers_) { names.push_back(entry.first); // a std::map is already sorted } return names;}
// Each maker is a lambda: `[]` captures nothing, there are no parameters,// and the body creates one exporter. The lambda is stored as a Maker and// only runs later, each time make() is asked for that format.ExporterRegistry standard_exporters() { ExporterRegistry registry; registry.add("txt", [] { return std::make_unique<TextExporter>(); }); registry.add("md", [] { return std::make_unique<MarkdownExporter>(); }); registry.add("html", [] { return std::make_unique<HtmlExporter>(); }); return registry;}How this code works: ExporterRegistry: add and make
The registry is a table with one row per format. Each row pairs a name with a maker: a small function, stored but not yet run, that creates one new exporter whenever it is called.
Filling the table. standard_exporters() calls add three times.
After those calls, the map holds these rows (a std::map keeps them in
alphabetical order, whatever order they were added in):
| Name | Maker, when called, returns |
|---|---|
html |
a new HtmlExporter |
md |
a new MarkdownExporter |
txt |
a new TextExporter |
Each add checks before it changes anything: an empty name or an empty
maker throws, and so does a name that is already a row. Only when every
check has passed does emplace add the row. So a refused add leaves
the table exactly as it was.
Using the table. make("html") does three things:
makers_.find("html")looks for the row. It returns an iterator, which works like a pointer to the row, ormakers_.end()if there is no such row.- If there is no row,
makebuilds the list of names fromformats()and throws. Formake("pdf")on the table above, the message isunknown format 'pdf'; supported: html, md, txt. The list is read from the table, so it is always up to date. - Otherwise
found->secondis the maker, andfound->second()calls it. Thehtmlmaker runsstd::make_unique<HtmlExporter>(), and the new exporter comes back in astd::unique_ptr. If a maker returned an empty pointer instead,makethrows, naming the format. Otherwise it returns the pointer, and the caller now owns the exporter.
Adding a format later. registry.add("outline", ...) in main adds
a fourth row. After it, make("outline") finds that row and runs its
maker, exactly as above. Nothing in registry.cpp changed: the new
format is new data, not new code.
The registry turns the if chain into data: a std::map from a
format name to a Maker, a std::function that creates one kind of
exporter each time it is called. That is what FR-4 needs: a plugin adds
a row, and nothing in this file changes. Some details:
std::less<>makes the map’s lookup accept astd::string_viewwithout first building astd::string.- The registry checks its rows. An empty name, an empty
std::function, or a duplicate is refused byadd, when it is registered. A maker that returns null is caught bymake, which names the format, instead of crashing later inrender. - The error message is built from the table.
makelists the formats fromformats(), so FR-3’s list cannot drift. Form 1’s hard-coded"supported: html, md, txt"is a second copy of itsifchain, and can. - Each
makecall creates a new exporter, owned by the caller. The registry owns only the makers. - The registry is an ordinary object, created by
standard_exporters()and owned by the app. There is no global registry. A test builds its own and can add a fake (NFR-1).
The client: one function for both callers
Section titled “The client: one function for both callers”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// "notes/report.md" -> "md"; "" if the name has no extension.// Only the part after the last '/' is looked at, and a name whose last// dot is its first character (".profile") has no extension. The result is a view// into `file_name`'s characters, not a copy, so it is valid only while// the string that was passed in still exists.std::string_view extension_of(std::string_view file_name);
// What both the command line and the "Save as" dialog call.// export_as: render `document` in the named format ("md", ...).// export_to_file_name: the same, with the format taken from the file// name's extension ("out/notes.html" -> "html").// Both take the registry by const reference: they only read it, asking it// to make an exporter. Both throw std::invalid_argument, from// registry.make, when the format is not registered.std::string export_as(const ExporterRegistry& registry, const Document& document, std::string_view format);std::string export_to_file_name(const ExporterRegistry& registry, const Document& document, std::string_view file_name);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Two steps: drop the folders, then take what follows the last dot.// substr on a string_view makes a smaller view of the same characters,// so nothing is copied.std::string_view extension_of(std::string_view file_name) { // The position of the last '/', or npos ("not found") if there is none. // `base` is then the bare file name: "notes/report.md" -> "report.md". const auto slash = file_name.find_last_of('/'); const std::string_view base = slash == std::string_view::npos ? file_name : file_name.substr(slash + 1); // Searching only `base` is what makes "v1.2/README" have no extension: // its dot is in the folder name, which has already been dropped. const auto dot = base.rfind('.'); if (dot == std::string_view::npos || dot == 0) { // ".profile" has no extension return {}; // an empty view: "" } return base.substr(dot + 1); // "backup.tar.gz" -> "gz"}// The client: it names no concrete exporter class. It asks the registry// for one (which may throw std::invalid_argument), uses it once, and lets// it go. `const std::unique_ptr` means this pointer is never reset or// handed on; it owns the exporter until the end of the function.std::string export_as(const ExporterRegistry& registry, const Document& document, std::string_view format) { const std::unique_ptr<Exporter> exporter = registry.make(format); return exporter->render(document);} // the exporter is destroyed here; nobody else holds it
// The dialog's path: the same as export_as, after reading the format from// the file name. A name with no extension asks for format "", which no// registry can hold (add refuses an empty name), so it throws as unknown.std::string export_to_file_name(const ExporterRegistry& registry, const Document& document, std::string_view file_name) { return export_as(registry, document, extension_of(file_name));}How this code works: extension_of
extension_of works in two steps, and both only look at the
characters: every substr on a std::string_view is a smaller view of
the same characters, so nothing is copied.
- Drop the folders.
find_last_of('/')gives the position of the last slash. If there is one,baseis everything after it; otherwisebaseis the whole name. - Take what follows the last dot in
base.rfind('.')gives the position of the last dot. If there is none, or the last dot is the very first character ofbase(as in.profile), the answer is empty. Otherwise it is everything after that dot.
The names from the tests and main, with positions counted from 0:
file_name |
last / |
base |
last . in base |
result |
|---|---|---|---|---|
notes/report.md |
5 | report.md |
6 | md |
out/notes.html |
3 | notes.html |
5 | html |
backup.tar.gz |
none | whole name | 10 | gz |
v1.2/README |
4 | README |
none | empty |
.profile |
none | whole name | 0 | empty |
The v1.2/README row is why step 1 comes first: searching the whole
name would find the dot in the folder v1.2 and give 2/README.
export_to_file_name passes the result straight to export_as, while
file_name is still alive, so the view is safe to use there. An empty
result asks the registry for format "", and add never accepts an
empty name, so that is always an unknown format.
export_as is what the command line calls; export_to_file_name is
what the dialog calls. Both go through the same registry, so FR-2 is
now true by construction, and a test checks it for every registered
format. export_as depends only on Exporter and the registry, never
on a concrete exporter. extension_of looks only at the last part of
the path, so v1.2/README has no extension, and it treats .profile
as a name without one. Its limits are deliberate: it splits paths only
on /, and it is case-sensitive, so plan.MD is an unknown format. It
returns a view into its argument, so do not keep the result past a
temporary argument.
Form 3: the classic Factory Method
Section titled “Form 3: the classic Factory Method”The classic form solves a slightly different problem. A base class does some shared work, needs an object to finish it, and leaves the choice of that object’s class to its derived classes:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The classic form: a base class does shared work and asks its// subclasses, through a virtual function, for the object it needs.// Here the shared work is "add an About section and render", and the// object it needs is an Exporter; which kind is up to the subclass.class ReportWriter {public: virtual ~ReportWriter() = default; // `= delete`: writers cannot be copied or assigned. They are used // through a base class, where copying would slice (see the idiom // reference on = default and = delete). ReportWriter(const ReportWriter&) = delete; ReportWriter& operator=(const ReportWriter&) = delete;
// Adds an "About this report" section, then renders the result. // Not virtual: every writer does the same steps, in the same order. // The caller's `document` is read only; the section goes on a copy. std::string write(const Document& document, const std::string& author) const;
protected: // Protected: only a derived writer can be created, never a bare // ReportWriter (which is abstract anyway, because of the `= 0` below). ReportWriter() = default;
private: // Private and virtual: write() calls it, and a subclass overrides it, // but no outside code can call it. Each call returns a new exporter // that the caller (write) owns. virtual std::unique_ptr<Exporter> create_exporter() const = 0; // the factory method};
// A writer whose reports come out as Markdown. Its only job is to answer// create_exporter; it inherits write unchanged.class MarkdownReportWriter final : public ReportWriter {private: std::unique_ptr<Exporter> create_exporter() const override;};
// The same for HTML.class HtmlReportWriter final : public ReportWriter {private: std::unique_ptr<Exporter> create_exporter() const override;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The shared steps. Only step 3 differs between subclasses.std::string ReportWriter::write(const Document& document, const std::string& author) const { // 1. Copy the document (its title and every section and paragraph). Document report = document; // a copy: the caller's document is not changed // 2. Append one more section. The braces make a temporary Section // (heading "About this report", and a list of one paragraph, // "Written by <author>."), which push_back then moves into the vector. report.sections.push_back({"About this report", {"Written by " + author + "."}}); // 3. The factory method. This is a virtual call, so it runs the // create_exporter of the object's real class: a MarkdownReportWriter // gets a MarkdownExporter. write itself never names a concrete class. const std::unique_ptr<Exporter> exporter = create_exporter(); // 4. Render the copy. The exporter and the copy are destroyed when // write returns; only the text is kept. return exporter->render(report);}
std::unique_ptr<Exporter> MarkdownReportWriter::create_exporter() const { return std::make_unique<MarkdownExporter>();}
std::unique_ptr<Exporter> HtmlReportWriter::create_exporter() const { return std::make_unique<HtmlExporter>();}How this code works: ReportWriter::write and create_exporter
Follow main’s call writer.write(notes, "Sam"), where writer is a
MarkdownReportWriter.
writeis defined only inReportWriter, so that version runs. It copiesnotesintoreport, so the caller’s document is never changed.- It appends one section to the copy: heading
About this report, one paragraph,Written by Sam.. - It calls
create_exporter(). Insidewrite, the code only knows it is aReportWriter, butcreate_exporteris virtual, so C++ runs the version of the object’s real class:MarkdownReportWriter::create_exporter, which returns a newMarkdownExporter. For anHtmlReportWriter, the same line would produce anHtmlExporter. - It renders the copy with that exporter and returns the text. When
writereturns, theunique_ptrdestroys the exporter and the copy is destroyed too. The output ends with## About this report, a blank line, andWritten by Sam., which is the last block of the program’s output below.
write never names a concrete exporter: the subclass chooses, and the
base class does the rest. Because create_exporter is private, nothing
but ReportWriter’s own code (here, write) can call it.
write is the shared work: it copies the document, adds an “About this
report” section, and renders. It calls create_exporter, the factory
method, to get the exporter. MarkdownReportWriter and
HtmlReportWriter exist only to answer that call. This is
Template Method with “create an object”
as the step that varies, and the same two rules apply: the virtual
function is private, because only write should call it, and it must
never be called from ReportWriter’s constructor, where the derived
part does not exist yet.
Be honest about this example: one subclass per format is heavy. A
ReportWriter that took a Maker (or an exporter) as a constructor
parameter would do the same job with no subclasses. The classic form
fits when the derived classes exist anyway for other reasons, as in
a framework where you already derive from its Document or Dialog
class and it asks your class to create the parts it needs.
Ownership and lifetime
Section titled “Ownership and lifetime”| Object | Owner | Lives |
|---|---|---|
| a created exporter | the caller, through std::unique_ptr |
until the caller lets it go; in export_as, one call |
| the registry | the app (main), as a local object |
as long as anyone may export |
| a maker in the registry | the registry, inside its std::map |
as long as the registry |
a ReportWriter |
whoever created it; not copyable | its owner decides; it holds no exporter between calls |
No creator keeps a pointer to what it created, so there is nothing to dangle when the caller destroys its exporter. One caution for makers: a lambda that captures something (for example, a reference to a plugin’s settings object) must not outlive it. The registry stores the lambda, so whatever it captures by reference must live at least as long as the registry.
One export, step by step
Section titled “One export, step by step”Text description of the diagram
The Save as dialog calls export_to_file_name with out/notes.html. extension_of gives html, and export_to_file_name calls export_as with the registry, the document, and html. export_as asks the ExporterRegistry to make html; the html maker creates an HtmlExporter, and the registry returns a unique_ptr to it. export_as calls render with the document and gets the HTML text back. The unique_ptr is destroyed, and so is the exporter. The HTML text is returned to export_to_file_name, and from there to the dialog.
Diagram source (Mermaid)
sequenceDiagram
participant D as Save as dialog
participant X as export_to_file_name
participant A as export_as
participant R as ExporterRegistry
participant H as HtmlExporter
D->>X: out/notes.html
X->>X: extension_of gives html
X->>A: export_as(registry, document, html)
A->>R: make(html)
R->>H: the html maker creates it
R-->>A: unique_ptr to the exporter
A->>H: render(document)
H-->>A: the HTML text
A->>A: unique_ptr destroyed, so is the exporter
A-->>X: the HTML text
X-->>D: the HTML textVerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A format added from outside: only the title and the headings.// It is written in main.cpp, not in exporters.hpp or registry.cpp, to// stand for a plugin: a new class derived from Exporter, which reaches// the app only through registry.add below.class OutlineExporter final : public Exporter {public: std::string render(const Document& document) const override { std::string out = document.title + '\n'; for (const Section& section : document.sections) { out += "- " + section.heading + '\n'; } return out; }};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A document built with nested braces: the title, then a list of// sections, each a heading and a list of paragraphs. "Goals" has two// paragraphs (the second has a < and an & for the HTML to escape);// "Risks" has one.const Document notes{"Q3 plan", {{"Goals", {"Ship the export feature.", "Keep load time < 2 s & fix crashes."}}, {"Risks", {"Two people on leave in August."}}}};// The app owns its registry: an ordinary local object, not a global.// Not const, because a format is added to it further down.ExporterRegistry registry = standard_exporters();
// The command line's path (a format name), then the dialog's path (a// file name). Both go through the same registry.std::cout << export_as(registry, notes, "md") << "---\n";std::cout << export_to_file_name(registry, notes, "out/notes.html") << "---\n";// "pdf" is not registered, so make throws before anything is// rendered; the catch prints the message, which lists the formats.try { export_to_file_name(registry, notes, "notes.pdf");} catch (const std::invalid_argument& error) { std::cout << "error: " << error.what() << "\n---\n";}
// The plugin's one line: a new row in the table. No exporting code// changed, yet a file name ending in .outline now works.registry.add("outline", [] { return std::make_unique<OutlineExporter>(); });std::cout << export_to_file_name(registry, notes, "notes.outline") << "---\n";VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The classic form: choosing the subclass chooses the exporter.// write adds the About section to a copy, so `notes` is unchanged.const MarkdownReportWriter writer;std::cout << writer.write(notes, "Sam");# Q3 plan
## Goals
Ship the export feature.
Keep load time < 2 s & fix crashes.
## Risks
Two people on leave in August.---<h1>Q3 plan</h1><h2>Goals</h2><p>Ship the export feature.</p><p>Keep load time < 2 s & fix crashes.</p><h2>Risks</h2><p>Two people on leave in August.</p>---error: unknown format 'pdf'; supported: html, md, txt---Q3 plan- Goals- Risks---# Q3 plan
## Goals
Ship the export feature.
Keep load time < 2 s & fix crashes.
## Risks
Two people on leave in August.
## About this report
Written by Sam.Read the output against the requirements:
- The first two blocks are Markdown, from the format name
md, and HTML, from the file nameout/notes.html(FR-1, FR-2). The HTML version escapes<and&. notes.pdfis an error that nameshtml, md, txt(FR-3).- After
mainaddsoutline, a file name ending in.outlineworks, and no exporting code changed (FR-4). - The last block comes from the classic form: Markdown, with the
“About this report” section that
ReportWriter::writeadds.
The tests check each requirement, including that both callers agree for every registered format:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// static_assert checks a condition while the program is compiled: if it// is false, the build fails. std::is_abstract_v<Exporter> is true because// render is pure virtual, so no plain Exporter can be created. Exporter's// copy assignment is protected, so outside code cannot assign one// Exporter over another and std::is_copy_assignable_v is false.static_assert(std::is_abstract_v<Exporter>);static_assert(!std::is_copy_assignable_v<Exporter>); // no slicing assignment through a base
// Form 1. Each name gives the right class, recognised by the start of// its output, and an unknown name throws. make_exporter(...)->render(...)// creates a temporary exporter, uses it, and destroys it in one line.LLD_TEST(the_factory_function_makes_the_exporter_for_each_format) { LLD_CHECK(starts_with(make_exporter("txt")->render(sample), "Plan\n====")); LLD_CHECK(starts_with(make_exporter("md")->render(sample), "# Plan")); LLD_CHECK(starts_with(make_exporter("html")->render(sample), "<h1>Plan</h1>")); LLD_CHECK_THROWS(make_exporter("pdf"), std::invalid_argument);}
// Form 2 against form 1: for every format in the registry, both give// exactly the same text, and there are exactly three formats.// LLD_CHECK_EQ(actual, expected) fails unless the two are equal, and on// failure prints both values. std::size_t{3} makes the 3 the same type as// size() returns, so the comparison is between two values of one type.LLD_TEST(the_registry_and_the_factory_function_agree_on_the_standard_formats) { const ExporterRegistry registry = standard_exporters(); for (const std::string& format : registry.formats()) { LLD_CHECK_EQ(registry.make(format)->render(sample), make_exporter(format)->render(sample)); } LLD_CHECK_EQ(registry.formats().size(), std::size_t{3});}
// FR-2: the two callers cannot disagree any more. For each format, the// dialog's path with "out/plan.<format>" gives the same text as the// command line's path with the bare format name.LLD_TEST(the_command_line_and_the_file_name_now_give_the_same_result) { const ExporterRegistry registry = standard_exporters(); for (const std::string& format : registry.formats()) { LLD_CHECK_EQ(export_to_file_name(registry, sample, "out/plan." + format), export_as(registry, sample, format)); }}
// FR-3: an unknown format is refused, and the message is checked word// for word. The try/catch keeps the message so it can be compared; if// nothing were thrown, `message` would stay empty and the check would// fail. "README" has no extension, so it asks for format "" and throws.LLD_TEST(an_unknown_format_is_an_error_that_names_the_supported_ones) { const ExporterRegistry registry = standard_exporters(); std::string message; try { export_to_file_name(registry, sample, "plan.pdf"); } catch (const std::invalid_argument& error) { message = error.what(); } LLD_CHECK_EQ(message, std::string{"unknown format 'pdf'; supported: html, md, txt"}); LLD_CHECK_THROWS(export_to_file_name(registry, sample, "README"), std::invalid_argument);}
// The edge cases of extension_of: a folder in front, two dots (the last// one counts), a dot only in the folder name, and a leading dot. The// string_view results are copied into std::string so LLD_CHECK_EQ can// compare and print them.LLD_TEST(extension_of_reads_only_the_last_part_of_the_name) { LLD_CHECK_EQ(std::string{extension_of("notes/report.md")}, std::string{"md"}); LLD_CHECK_EQ(std::string{extension_of("backup.tar.gz")}, std::string{"gz"}); LLD_CHECK_EQ(std::string{extension_of("v1.2/README")}, std::string{""}); LLD_CHECK_EQ(std::string{extension_of(".profile")}, std::string{""});}
// FR-4 and NFR-1: a test adds its own format to its own registry.// FakeExporter (defined earlier in this file) renders "fake:" followed by// the title, so the result shows that the fake's maker ran.LLD_TEST(code_outside_the_registry_can_add_a_format) { ExporterRegistry registry = standard_exporters(); registry.add("fake", [] { return std::make_unique<FakeExporter>(); }); LLD_CHECK_EQ(export_as(registry, sample, "fake"), std::string{"fake:Plan"}); LLD_CHECK_EQ(registry.formats().size(), std::size_t{4});}
// Each kind of bad row is refused. In order: a name that is already// taken ("md"), an empty name, and an empty maker (nullptr makes an empty// std::function). The last maker is accepted by add, because it is a real// function, but it returns an empty unique_ptr, so make refuses it.LLD_TEST(the_registry_refuses_bad_registrations) { ExporterRegistry registry = standard_exporters(); LLD_CHECK_THROWS(registry.add("md", [] { return std::make_unique<FakeExporter>(); }), std::invalid_argument); LLD_CHECK_THROWS(registry.add("", [] { return std::make_unique<FakeExporter>(); }), std::invalid_argument); LLD_CHECK_THROWS(registry.add("none", nullptr), std::invalid_argument); registry.add("broken", [] { return std::unique_ptr<Exporter>{}; }); LLD_CHECK_THROWS(registry.make("broken"), std::invalid_argument);}
// Asking twice for "md" gives two separate objects: get() returns the// address each unique_ptr holds, and the addresses differ. The registry// hands out new exporters; it does not share one.LLD_TEST(each_call_makes_a_new_exporter_owned_by_the_caller) { const ExporterRegistry registry = standard_exporters(); const std::unique_ptr<Exporter> first = registry.make("md"); const std::unique_ptr<Exporter> second = registry.make("md"); LLD_CHECK(first.get() != second.get());}
// Every character the HTML exporter escapes is used: & in the title, < and// > in the heading, and two double quotes in the paragraph (each written \"// inside a C++ string literal). HtmlExporter{} creates a temporary exporter directly,// with no factory, which is fine in a test of that one class.LLD_TEST(html_export_escapes_special_characters) { const Document tricky{"A & B", {{"<script>", {"say \"hi\""}}}}; LLD_CHECK_EQ(HtmlExporter{}.render(tricky), std::string{"<h1>A & B</h1>\n<h2><script></h2>\n" "<p>say "hi"</p>\n"});}
// Form 3. Each writer ends its output with the added section in its own// format (ends_with is a C++20 std::string function), and afterwards// `sample` still has its one section: write changed only its copy.LLD_TEST(the_classic_writer_adds_its_section_without_changing_the_document) { const MarkdownReportWriter markdown; const HtmlReportWriter html; const std::string text = markdown.write(sample, "Sam"); LLD_CHECK(text.ends_with("## About this report\n\nWritten by Sam.\n")); LLD_CHECK(html.write(sample, "Sam").ends_with("<p>Written by Sam.</p>\n")); LLD_CHECK_EQ(sample.sections.size(), std::size_t{1});}Choosing a form
Section titled “Choosing a form”| Situation | Use |
|---|---|
| The caller already knows the exact class | a constructor call; no factory |
| The caller knows which object to use, and something else should create it | pass the object in (dependency injection) |
| A choice by name or setting, made in more than one place, from a fixed set | a factory function |
| The set grows from outside (plugins, tests, configuration) | a registry of makers, owned by the app |
| A base class’s shared work needs an object, and derived classes exist anyway | the classic Factory Method |
| The object needs many settings checked before it exists | not a factory problem; see Builder |
A useful test: who knows the concrete class? If it is the caller, no factory is needed. If it is “whoever knows the format names”, that knowledge deserves one home, and the forms above are ways to give it one.
Factory vs Strategy. They often appear together, as here: the exporters are interchangeable strategies, and the factory chooses which one to create. Strategy is about using one of several algorithms; a factory is about creating one of several classes. If the code were handed an exporter and never chose its class, that would be Strategy alone.
When to use it
Section titled “When to use it”Use a factory (in one of its forms) when:
- the concrete class is chosen at run time, from a name, a setting, or input;
- the same choice would otherwise be made in more than one place;
- code you do not control must be able to add classes to the family;
- callers should depend only on an interface, so they can be tested with fakes.
- An indirection. A reader of
export_asmust look at the registry to see which class runs. Good names and an error message that lists the formats help. - A registry moves errors to run time. A misspelt format name is an
exception, not a compile error. That is fine for names that come from
users and files; for names fixed in code, an
enumand a factory function let the compiler check them. - The classic form costs a class per product, and a reader must find which subclass is in use.
Common misuse
Section titled “Common misuse”- A factory for one class.
GreetingFormatterFactory::create()that can only ever return one type is a constructor with extra steps. See the cost of abstraction. - Owning raw pointers.
Exporter* make_exporter(...)hands the caller adeleteto remember. Returnstd::unique_ptr. std::shared_ptrby default. It suggests the factory or someone else keeps a share. Returnstd::unique_ptr, and let a caller that needs sharing convert it.- A global, self-registering registry, with the problems in the warning above, plus hidden global state that tests cannot replace.
- A factory that also configures everything. When creation needs a long list of optional settings and checks, the factory is turning into a builder.
When the requirements change
Section titled “When the requirements change”- “Add AsciiDoc.” A new exporter class and one
addline instandard_exporters(). With the factory function, one moreif; with the classic form, a newReportWritersubclass too. See the exercise. - “Formats need options (HTML with or without a style sheet).”
Capture the options when the format is registered:
htmlandhtml-styledas two rows, or a lambda that captures a settings object that outlives the registry. Callers do not change. If each export must choose its own options,makehas to take them, and then the callers do change. - “Let users pick from a list of formats.”
formats()already returns the registered names, sorted, so the dialog builds its list from the same table that creates exporters.
Exercise
Section titled “Exercise”Exercise: Add a format, and justify the approach
- Add an AsciiDoc exporter, format
adoc(a title line starting with=, headings starting with==, and a blank line before each paragraph). For each of the three forms, list what changes. - A plugin team ships two formats in a separate library. Which form should the app use, and how should the plugin’s formats get into it?
- A teammate suggests that the plugin register itself with
[[maybe_unused]] static const bool registered = (global_registry().add(...), true);in its source file. Give two things that can go wrong. - A 200-line command-line tool supports exactly
txtandmd, and creates the exporter in one place. Which form should it use?
Show the explained answer
1.
// One more concrete product. Like the other exporters it derives from// Exporter, overrides render, and holds no data.class AsciiDocExporter final : public Exporter {public: std::string render(const Document& document) const override { // The title line: "= " then the title. std::string out = "= " + document.title + "\n"; for (const Section& section : document.sections) { // A blank line, then "== " and the heading. out += "\n== " + section.heading + "\n"; for (const std::string& paragraph : section.paragraphs) { // A blank line before each paragraph. out += "\n" + paragraph + "\n"; } } return out; }};With the registry: the class, plus
registry.add("adoc", [] { return std::make_unique<AsciiDocExporter>(); });
in standard_exporters(). Nothing else changes, and a file name ending
in .adoc works in both callers at once. The tests that pin the
standard list (its size and the error-message text) need the new name.
And if the app also keeps make_exporter, it needs the new if too,
or the test that the two agree fails: two creators for the same set is
the drift this page started with, so a real app keeps only one. With
the factory function:
the class, plus one more if in make_exporter, and the list of
supported formats in its error message. With the classic form: the
class, plus an AsciiDocReportWriter subclass, and whoever chooses
which writer to create must learn about it, which is the original
problem again, one level up.
2. The registry. The app owns it, and the plugin library provides
one function, for example void register_formats(ExporterRegistry&),
which main calls after standard_exporters(). The app now names the
plugin once, in main, and nothing else in the app knows its classes.
A duplicate name is an error at start-up, not a silent override.
3. First, the order of initialization of global objects in
different source files is not specified, so registered may be
initialized before the registry it adds to, unless the registry is a
function-local static. Second, if the plugin is linked as a static
library and nothing refers to its source file, the linker can leave
that file out, so the registration never runs and the format is
missing with no error. Also, this registry’s add throws on a
duplicate; thrown while globals are being initialized, that calls
std::terminate before main starts, with no chance to report it. And
the registry is now global state that every test shares.
4. Neither a registry nor the classic form: one if (or a
switch on an enum) where the exporter is created is enough, since
the choice is made once and the set is fixed. If a second place starts
choosing an exporter, move the if into a factory function then.
Related patterns
Section titled “Related patterns”- Abstract Factory: creates a whole family of related objects that must match, instead of one object. See Abstract Factory.
- Strategy: the products here are strategies; a factory chooses which one to create. See Strategy.
- Template Method: the classic Factory Method is a template method whose varying step creates an object. See Template Method.
- Builder: for objects that need many settings before they exist. See Builder, and Factory Method vs Abstract Factory vs Builder.
Summary
Section titled “Summary”- When the same “which class?” choice is made in several places, the copies drift. Give that choice one home.
- In C++, a factory returns
std::unique_ptrto the interface: the caller owns the object, and the factory keeps nothing. - Use a factory function for a fixed set, a registry of makers owned by the app when code outside must add to the set, and the classic Factory Method when a base class’s shared work needs an object and its derived classes exist anyway.
- Avoid global self-registration; register explicitly from
main. - If the caller already knows the class, construct it. If it knows the object, pass the object in. Neither needs a factory.