On this page

Abstract Factory

Factory Method lets one product vary. Abstract Factory is what you reach for when several products have to vary together. You have a group of objects that only make sense in matching sets, and the danger isn't picking the wrong class. The danger is picking classes from different sets and mixing them.

Think of a database driver. A connection, a statement and a result set from the same driver work together. A PostgreSQL connection paired with an Oracle statement does not. Or a document generator: an HTML heading next to a Markdown link produces a broken page. Abstract Factory puts the choice of "which set" into one object. Everything created through that object belongs to the same set by construction, so mixing becomes impossible rather than merely unlikely.

The creational patterns page introduces the idea with a UI toolkit. This page builds it out fully: the before code, the structure, three implementations, a way to make mixing a compile error, the trade-off that decides whether the pattern is worth it, and real uses in JDBC, .NET, Spring and React.

CategoryCreational (object-based)
Also known asKit
SolvesCreating families of related objects that must be used together
Main costAdding a new kind of product means changing the interface and every factory
Modern formAn interface or record of factory functions, chosen once at the composition root

Intent

Provide an interface for creating families of related or dependent objects without specifying their concrete classes, so that a client configured with one factory only ever receives products from one family.

Two words in that sentence carry the weight. Families: there are several product types, such as heading, list and link. Related: each family's products are designed to work with each other, and mixing families is a bug.

The problem

A release-notes tool renders the same content as HTML for the website and as Markdown for the repository. The first version decides the format at every element.

import java.util.*;

enum Format { HTML, MARKDOWN }

class ReleaseNotes {
    private final Format format;
    ReleaseNotes(Format format) { this.format = format; }

    String heading(String text) {
        return format == Format.HTML ? "<h2>" + text + "</h2>" : "## " + text;
    }

    String bullets(List<String> items) {
        StringBuilder out = new StringBuilder(format == Format.HTML ? "<ul>" : "");
        for (String item : items) {
            out.append(format == Format.HTML ? "<li>" + item + "</li>" : "\n- " + item);
        }
        return out.append(format == Format.HTML ? "</ul>" : "").toString();
    }

    // Added months later by someone who forgot there are two formats.
    String link(String label, String url) {
        return "[" + label + "](" + url + ")";
    }

    String render(String version, List<String> changes, String url) {
        return heading(version) + bullets(changes) + link("Full changelog", url);
    }
}

public class Before {
    public static void main(String[] args) {
        String html = new ReleaseNotes(Format.HTML).render("v2.1", List.of("Faster search"), "/changes");
        if (!html.contains("[Full changelog](/changes)")) throw new AssertionError("bug should reproduce");
        System.out.println("HTML page with a Markdown link inside: " + html);
    }
}
class ReleaseNotes:
    def __init__(self, fmt: str) -> None:
        self.fmt = fmt

    def heading(self, text: str) -> str:
        return f"<h2>{text}</h2>" if self.fmt == "html" else f"## {text}"

    def bullets(self, items: list[str]) -> str:
        if self.fmt == "html":
            return "<ul>" + "".join(f"<li>{i}</li>" for i in items) + "</ul>"
        return "".join(f"\n- {i}" for i in items)

    def link(self, label: str, url: str) -> str:
        # Added later. Nobody remembered the format check.
        return f"[{label}]({url})"

    def render(self, version: str, changes: list[str], url: str) -> str:
        return self.heading(version) + self.bullets(changes) + self.link("Full changelog", url)


html = ReleaseNotes("html").render("v2.1", ["Faster search"], "/changes")
assert "[Full changelog](/changes)" in html     # the bug: mixed families
print("HTML page with a Markdown link inside:", html)

The problems:

  • The format decision is repeated at every element. Each method branches on the same flag. That's the same conditional in many places, which is a strong signal that the variation should be one object instead.
  • Consistency depends on memory. Nothing forces a new method to respect the format, so link silently produced Markdown inside HTML. In a larger codebase, this is how a "dark theme" ends up with one light dialog, or a test suite ends up with a real payment client next to fake repositories.
  • Adding a third format (say, plain text for email) means editing every method. Every edit risks breaking the two formats that already work.
  • The class has two responsibilities: the release-notes layout (heading, then bullets, then link) and the details of each output format.

Structure

classDiagram
    class DocumentFactory {
        <<interface>>
        +heading(text) Heading
        +link(label, url) Link
    }
    class HtmlFactory
    class MarkdownFactory
    class Heading {
        <<interface>>
        +render() String
    }
    class Link {
        <<interface>>
        +render() String
    }
    class HtmlHeading
    class MarkdownHeading
    class HtmlLink
    class MarkdownLink
    class ReleaseNotes {
        +render(release) String
    }
    DocumentFactory <|.. HtmlFactory
    DocumentFactory <|.. MarkdownFactory
    Heading <|.. HtmlHeading
    Heading <|.. MarkdownHeading
    Link <|.. HtmlLink
    Link <|.. MarkdownLink
    HtmlFactory ..> HtmlHeading : creates
    HtmlFactory ..> HtmlLink : creates
    MarkdownFactory ..> MarkdownHeading : creates
    MarkdownFactory ..> MarkdownLink : creates
    ReleaseNotes --> DocumentFactory : uses

The diagram shows two product types to keep it readable. The code below has three (heading, bullet list and link). Read the diagram as a grid: each row is a family (HTML, Markdown) and is one concrete factory, and each column is a product type (heading, link) and is one product interface. The client (ReleaseNotes) depends only on the abstract factory and the abstract products, never on a concrete class.

Participants

  • Abstract factory (DocumentFactory). Declares one creation method per product type.
  • Concrete factories (HtmlFactory, MarkdownFactory). Implement every creation method for one family. A concrete factory is the unit of consistency: it only ever returns its own family's products.
  • Abstract products (Heading, BulletList, Link). One interface per product type.
  • Concrete products (HtmlHeading, MarkdownLink and so on). One class per cell of the grid.
  • Client (ReleaseNotes). Receives a factory, usually through its constructor, and uses only the abstract types. It never chooses a family itself.

Behind these sits the composition root, the one place that reads configuration and picks the concrete factory. That's where the only switch on format remains.

Implementation

The three implementations below render the same release notes in both formats. They also escape HTML properly in the HTML family, a detail that shows why per-family behaviour belongs together: escaping is an HTML concern every HTML product must share, and Markdown needs different escaping.

import java.util.*;

interface Heading { String render(); }
interface BulletList { String render(); }
interface Link { String render(); }

interface DocumentFactory {
    Heading heading(String text);
    BulletList bullets(List<String> items);
    Link link(String label, String url);
}

// ---- HTML family ----------------------------------------------------------
final class HtmlFactory implements DocumentFactory {
    private static String esc(String s) {
        return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;");
    }
    public Heading heading(String text) { return () -> "<h2>" + esc(text) + "</h2>\n"; }
    public BulletList bullets(List<String> items) {
        return () -> {
            StringBuilder out = new StringBuilder("<ul>\n");
            for (String item : items) out.append("  <li>").append(esc(item)).append("</li>\n");
            return out.append("</ul>\n").toString();
        };
    }
    public Link link(String label, String url) {
        return () -> "<a href=\"" + esc(url) + "\">" + esc(label) + "</a>\n";
    }
}

// ---- Markdown family ------------------------------------------------------
final class MarkdownFactory implements DocumentFactory {
    private static String esc(String s) { return s.replace("*", "\\*").replace("_", "\\_"); }
    public Heading heading(String text) { return () -> "## " + esc(text) + "\n\n"; }
    public BulletList bullets(List<String> items) {
        return () -> {
            StringBuilder out = new StringBuilder();
            for (String item : items) out.append("- ").append(esc(item)).append("\n");
            return out.append("\n").toString();
        };
    }
    public Link link(String label, String url) { return () -> "[" + esc(label) + "](" + url + ")\n"; }
}

// ---- Client: knows the layout, not the format -----------------------------
record Release(String version, List<String> changes, String changelogUrl) {}

final class ReleaseNotes {
    private final DocumentFactory doc;
    ReleaseNotes(DocumentFactory doc) { this.doc = doc; }

    String render(Release r) {
        return doc.heading(r.version()).render()
             + doc.bullets(r.changes()).render()
             + doc.link("Full changelog", r.changelogUrl()).render();
    }
}

public class Main {
    // Composition root: the only place that knows the concrete families.
    static DocumentFactory factoryFor(String format) {
        return switch (format) {
            case "html" -> new HtmlFactory();
            case "md" -> new MarkdownFactory();
            default -> throw new IllegalArgumentException("unknown format: " + format);
        };
    }

    public static void main(String[] args) {
        Release release = new Release("v2.1", List.of("Faster search", "Fix <script> escaping"), "/changes");

        String html = new ReleaseNotes(factoryFor("html")).render(release);
        String md = new ReleaseNotes(factoryFor("md")).render(release);

        if (!html.startsWith("<h2>v2.1</h2>")) throw new AssertionError(html);
        if (!html.contains("&lt;script&gt;")) throw new AssertionError("HTML family escapes");
        if (!html.contains("<a href=\"/changes\">Full changelog</a>")) throw new AssertionError(html);
        if (html.contains("](")) throw new AssertionError("no Markdown inside HTML");
        if (!md.equals("## v2.1\n\n- Faster search\n- Fix <script> escaping\n\n[Full changelog](/changes)\n"))
            throw new AssertionError(md);
        System.out.print(html + "---\n" + md);
    }
}
import html as html_lib
from dataclasses import dataclass
from typing import Protocol


class Heading(Protocol):
    def render(self) -> str: ...


class BulletList(Protocol):
    def render(self) -> str: ...


class Link(Protocol):
    def render(self) -> str: ...


class DocumentFactory(Protocol):
    def heading(self, text: str) -> Heading: ...
    def bullets(self, items: list[str]) -> BulletList: ...
    def link(self, label: str, url: str) -> Link: ...


# ---- HTML family ----------------------------------------------------------
@dataclass(frozen=True)
class HtmlHeading:
    text: str

    def render(self) -> str:
        return f"<h2>{html_lib.escape(self.text)}</h2>\n"


@dataclass(frozen=True)
class HtmlBullets:
    items: tuple[str, ...]

    def render(self) -> str:
        lis = "".join(f"  <li>{html_lib.escape(i)}</li>\n" for i in self.items)
        return f"<ul>\n{lis}</ul>\n"


@dataclass(frozen=True)
class HtmlLink:
    label: str
    url: str

    def render(self) -> str:
        return f'<a href="{html_lib.escape(self.url)}">{html_lib.escape(self.label)}</a>\n'


class HtmlFactory:
    def heading(self, text: str) -> Heading:
        return HtmlHeading(text)

    def bullets(self, items: list[str]) -> BulletList:
        return HtmlBullets(tuple(items))

    def link(self, label: str, url: str) -> Link:
        return HtmlLink(label, url)


# ---- Markdown family ------------------------------------------------------
def md_escape(s: str) -> str:
    return s.replace("*", "\\*").replace("_", "\\_")


@dataclass(frozen=True)
class MarkdownHeading:
    text: str

    def render(self) -> str:
        return f"## {md_escape(self.text)}\n\n"


@dataclass(frozen=True)
class MarkdownBullets:
    items: tuple[str, ...]

    def render(self) -> str:
        return "".join(f"- {md_escape(i)}\n" for i in self.items) + "\n"


@dataclass(frozen=True)
class MarkdownLink:
    label: str
    url: str

    def render(self) -> str:
        return f"[{md_escape(self.label)}]({self.url})\n"


class MarkdownFactory:
    def heading(self, text: str) -> Heading:
        return MarkdownHeading(text)

    def bullets(self, items: list[str]) -> BulletList:
        return MarkdownBullets(tuple(items))

    def link(self, label: str, url: str) -> Link:
        return MarkdownLink(label, url)


# ---- Client ---------------------------------------------------------------
@dataclass(frozen=True)
class Release:
    version: str
    changes: list[str]
    changelog_url: str


class ReleaseNotes:
    def __init__(self, doc: DocumentFactory) -> None:
        self._doc = doc

    def render(self, r: Release) -> str:
        return (self._doc.heading(r.version).render()
                + self._doc.bullets(r.changes).render()
                + self._doc.link("Full changelog", r.changelog_url).render())


FACTORIES: dict[str, DocumentFactory] = {"html": HtmlFactory(), "md": MarkdownFactory()}

release = Release("v2.1", ["Faster search", "Fix <script> escaping"], "/changes")
html_out = ReleaseNotes(FACTORIES["html"]).render(release)
md_out = ReleaseNotes(FACTORIES["md"]).render(release)

assert html_out.startswith("<h2>v2.1</h2>")
assert "&lt;script&gt;" in html_out and "](" not in html_out
assert md_out == "## v2.1\n\n- Faster search\n- Fix <script> escaping\n\n[Full changelog](/changes)\n"
print(html_out + "---\n" + md_out, end="")
import assert from "node:assert/strict";

interface Heading { render(): string }
interface BulletList { render(): string }
interface Link { render(): string }

interface DocumentFactory {
  heading(text: string): Heading;
  bullets(items: readonly string[]): BulletList;
  link(label: string, url: string): Link;
}

// ---- HTML family ----------------------------------------------------------
const esc = (s: string): string =>
  s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");

class HtmlFactory implements DocumentFactory {
  heading(text: string): Heading { return { render: () => `<h2>${esc(text)}</h2>\n` }; }
  bullets(items: readonly string[]): BulletList {
    return { render: () => `<ul>\n${items.map((i) => `  <li>${esc(i)}</li>\n`).join("")}</ul>\n` };
  }
  link(label: string, url: string): Link {
    return { render: () => `<a href="${esc(url)}">${esc(label)}</a>\n` };
  }
}

// ---- Markdown family: an object literal satisfies the interface too ------
const mdEsc = (s: string): string => s.replace(/\*/g, "\\*").replace(/_/g, "\\_");

const markdownFactory: DocumentFactory = {
  heading: (text) => ({ render: () => `## ${mdEsc(text)}\n\n` }),
  bullets: (items) => ({ render: () => items.map((i) => `- ${mdEsc(i)}\n`).join("") + "\n" }),
  link: (label, url) => ({ render: () => `[${mdEsc(label)}](${url})\n` }),
};

// ---- Client ---------------------------------------------------------------
type Release = Readonly<{ version: string; changes: readonly string[]; changelogUrl: string }>;

class ReleaseNotes {
  constructor(private readonly doc: DocumentFactory) {}
  render(r: Release): string {
    return this.doc.heading(r.version).render()
      + this.doc.bullets(r.changes).render()
      + this.doc.link("Full changelog", r.changelogUrl).render();
  }
}

// Composition root
const factories = { html: new HtmlFactory(), md: markdownFactory } satisfies Record<string, DocumentFactory>;

const release: Release = { version: "v2.1", changes: ["Faster search", "Fix <script> escaping"], changelogUrl: "/changes" };
const html = new ReleaseNotes(factories.html).render(release);
const md = new ReleaseNotes(factories.md).render(release);

assert.ok(html.startsWith("<h2>v2.1</h2>"));
assert.ok(html.includes("&lt;script&gt;") && !html.includes("]("));
assert.equal(md, "## v2.1\n\n- Faster search\n- Fix <script> escaping\n\n[Full changelog](/changes)\n");
console.log(html + "---\n" + md);

Things to notice:

  • The only conditional left is in the composition root (factoryFor in Java, the dictionary in Python, the factories object in TypeScript). It runs once. After that, every product the client creates comes from one family.
  • ReleaseNotes is now testable in isolation. Give it a fake factory whose products render H(v2.1) and L(Full changelog) and you can test the layout without caring about HTML.
  • Factories are stateless, so one instance per family is enough. That's why concrete factories are often shared. Inject a single instance rather than making it a Singleton.
  • Products don't have to be classes. The Java version uses lambdas for products, and the TypeScript Markdown family is a plain object literal. What makes it an Abstract Factory is the interface with one method per product type, implemented once per family. Class count doesn't matter.

Making mixing a compile-time error

The pattern prevents mixing as long as everyone goes through one factory. If products from two factories can meet (say a function takes a heading and a link from separate sources), the type system can still let the wrong combination through, because HtmlLink and MarkdownLink are both just Link. In languages with generics you can tag products with their family and make the compiler reject a mix.

import assert from "node:assert/strict";

type Family = "html" | "md";
interface Heading<F extends Family> { readonly family: F; render(): string }
interface Link<F extends Family> { readonly family: F; render(): string }

interface DocumentFactory<F extends Family> {
  heading(text: string): Heading<F>;
  link(label: string, url: string): Link<F>;
}

const html: DocumentFactory<"html"> = {
  heading: (t) => ({ family: "html", render: () => `<h2>${t}</h2>` }),
  link: (l, u) => ({ family: "html", render: () => `<a href="${u}">${l}</a>` }),
};
const md: DocumentFactory<"md"> = {
  heading: (t) => ({ family: "md", render: () => `## ${t}` }),
  link: (l, u) => ({ family: "md", render: () => `[${l}](${u})` }),
};

// F is inferred from the heading only (NoInfer, TypeScript 5.4+), so the link
// must come from the same family. Without NoInfer, TypeScript would happily
// widen F to "html" | "md" and accept the mix.
function footer<F extends Family>(h: Heading<F>, l: Link<NoInfer<F>>): string {
  return h.render() + "\n" + l.render();
}

assert.equal(footer(html.heading("More"), html.link("Docs", "/docs")), '<h2>More</h2>\n<a href="/docs">Docs</a>');

// @ts-expect-error: an HTML heading with a Markdown link does not type-check
footer(html.heading("More"), md.link("Docs", "/docs"));

console.log("mixed families are rejected at compile time");

The @ts-expect-error line is a test in its own right: if the types ever stop rejecting the mix, the compiler reports that the expected error is missing. Java can do the same with a type parameter on each product interface (Heading<F extends Family> with marker types), although it's noisier. This is rarely necessary in practice, but it's a good answer to an interviewer who asks how you'd guarantee that families are never mixed.

The central trade-off: families versus products

Abstract Factory makes one kind of change cheap and another expensive. In the grid of families (rows) and product types (columns):

ChangeWhat you touchCost
Add a family (plain text for email)One new concrete factory and its productsCheap and additive: no existing class changes
Add a product type (a table)The abstract factory interface, every concrete factory, plus new product classesExpensive: every family must change

This is a small instance of what programming-language people call the expression problem. Object-oriented designs make it easy to add new variants of a fixed set of operations, and hard to add new operations. Before choosing Abstract Factory, ask which axis changes more often in your domain. If new product types arrive every sprint and new families arrive once a year, the pattern fights you.

Ways to soften the cost of adding a product type:

  • Default methods (Java) or a base class with a default implementation: add table(...) with a fallback that throws UnsupportedOperationException or renders something generic, then implement it family by family. This gets the code compiling, but trades a compile-time guarantee for a run-time failure, so use it as a migration step, not a permanent state.
  • A generic create(kind) method taking a product key. It's flexible, but you lose static typing for each product, and it's really a registry rather than an Abstract Factory.
  • Smaller factories. If products cluster into independent groups (text elements and media elements, say), split the factory so each change touches less.

Real-world uses

JDBC and Python DB-API. A JDBC Connection is a factory for Statement, PreparedStatement, CallableStatement and LOB objects. All of them come from the same driver, and you never combine a PostgreSQL connection with an Oracle statement because you never construct statements yourself. Python's DB-API does the same with connection.cursor(). The driver is the family, and the connection is the concrete factory.

.NET DbProviderFactory. This is the textbook case: CreateConnection(), CreateCommand(), CreateParameter(), CreateDataAdapter() and more, with one concrete factory per provider (for example SQL Server or SQLite providers). Code written against DbProviderFactory can switch databases by changing which factory it's given.

JAXP in the JDK. DocumentBuilderFactory.newInstance(), SAXParserFactory.newInstance() and TransformerFactory.newInstance() locate an implementation at run time (through system properties or the service-provider mechanism) and return a factory for that implementation's parsers or transformers. Each factory is small, but the idea is the same: application code depends on the abstract factory and never names the vendor's classes.

Spring profiles. A @Configuration class marked @Profile("test") that defines in-memory repositories, a fake clock and a stub payment client, next to a @Profile("prod") class defining the real ones, is an Abstract Factory expressed through the container. Activating a profile selects a whole family of beans at once, which avoids the classic bug of a test that accidentally uses one real external client.

MDX and React. MDXProvider (and the components prop on compiled MDX content) takes an object that maps Markdown elements such as h1, a and ul to React components. Swapping that object swaps the whole family used to render a document, which is close to the release-notes example above. Several React component libraries accept a similar components override map to replace a set of internal sub-components together.

AWT, historically. Early Java AWT used a Toolkit to create platform-specific peer objects for each component type (button peers, frame peers and so on), one family per operating system. Most of that peer API has since been removed from public use, but it's the origin of many textbook examples.

When NOT to use it, and the costs

  • There's only one family. Then there's nothing to keep consistent. Create the objects directly, or use a single Factory Method if one product varies.
  • The products don't constrain each other. If an HTML heading next to a Markdown link would be fine in your domain, you don't have a family, just several independent choices. Inject each dependency separately.
  • New product types arrive often. As shown above, each one means changing every factory. A registry of independent factories, or plain DI, will hurt less.
  • The factory is becoming a service locator. A ServiceFactory with twenty createX() methods that every class receives is a global grab-bag with a nicer name. Each client should depend only on the products it uses. The interface segregation principle applies to factories too.
  • Your DI container already handles environment-specific wiring. Profiles, modules or environment-specific registrations often make a hand-written Abstract Factory redundant. Write the factory by hand only when the choice of family happens at run time per operation (for example per tenant or per request), not once at startup.

Costs:

CostWhy it matters
Many classesFamilies × product types concrete classes, plus interfaces and factories
Expensive new product typesInterface change ripples through every family
IndirectionReading the client doesn't tell you which classes run
Lowest-common-denominator interfacesProducts must expose only what every family can support, so family-specific features are awkward to reach
  • Factory Method. Varies one product, typically through a subclass that overrides a creation method. Abstract Factory varies a family through a factory object passed to the client. Concrete factories are often implemented as a set of factory methods, which is why the two get confused.
  • Builder. Builds one complex object step by step and returns it at the end. Abstract Factory returns each product immediately and focuses on keeping several products consistent. A family can include builders: factory.newQuery() might return a dialect-specific query builder.
  • Prototype. A concrete factory can be implemented by cloning a set of prototype objects instead of having one class per family. This is useful when families are configured at run time (user-defined themes, say) rather than coded as classes.
  • Singleton. Concrete factories are usually stateless, so one per family is enough. Share that instance through injection instead of making the factory a classic singleton.
  • Bridge. Separates an abstraction from its implementation so both can vary. An Abstract Factory is a common way to create and configure the implementation side of a bridge, for instance choosing all the platform-specific implementors at once.
  • Facade. A facade simplifies use of a subsystem, while an abstract factory hides which subsystem implementation you're using. They're often combined: a facade over a database layer may take a DbProviderFactory.
  • Dependency Injection. DI containers with profiles or modules can select a family of implementations at startup. Hand-written Abstract Factories remain useful when the family is chosen at run time and may differ from one call to the next.

The smell that suggests it

  • The same conditional on "which variant" appears in many methods, such as if (format == HTML), if (theme == DARK) or if (provider == AWS), and each branch creates or configures a different object.
  • A bug class of "mixed sets": a dark dialog in a light theme, a real email sender in a test that uses fake repositories, a SQL Server parameter object passed to a SQLite command.
  • A third variant is coming, and adding it would mean touching every one of those conditionals.
  • Several constructor parameters always change together. If every environment passes a matching ObjectStore, Queue and SecretStore, those three are a family, and one factory parameter would replace three.

The refactoring: extract an interface with one creation method per varying object, create one implementation per variant, move each branch's code into the matching factory, pass the factory to the client and delete the conditionals.

Interview questions

  1. "How is Abstract Factory different from Factory Method?" Factory Method varies one product, usually through inheritance (a subclass overrides a creation method). Abstract Factory varies a family of related products through composition: the client is given a factory object with one method per product type. Abstract Factory's methods are often factory methods.
  2. "What is the main weakness of Abstract Factory?" Adding a new product type requires changing the abstract interface and every concrete factory. Adding a new family is cheap. Pick the pattern only when families change more often than product types do.
  3. "How do you choose which concrete factory to use?" Once, at the composition root, from configuration, environment or a runtime key such as tenant or region, and inject it. Avoid scattering the choice through the code, which would recreate the conditionals the pattern removed.
  4. "Should the concrete factory be a singleton?" It's usually stateless, so one instance per family is enough, but make it a single injected instance rather than a class-enforced singleton, so tests can supply a fake factory.
  5. "Give a real example." JDBC: a Connection creates statements of the matching driver. .NET's DbProviderFactory is the canonical case. Spring profiles select a family of beans per environment.
  6. "How would you guarantee products from different families can't be combined?" Route all creation through one factory per client. For stronger guarantees, add a type parameter for the family to each product interface so a method that takes several products requires them to share it. Mixing then fails to compile.
  7. "Isn't this just dependency injection?" Partly. DI wires in implementations, often once at startup. Abstract Factory is a runtime object that creates products on demand and can be swapped per operation. In practice, the container injects the right concrete factory, and the client uses it to create products as needed.
  8. "In an LLD interview, where would you use it?" Anywhere the problem has a "mode" that changes several collaborators together: a game with themed board, pieces and sounds, a payment system where each region needs its own gateway, tax calculator and receipt format, or a test mode where clock, ID generator and notifier are all fakes. Say why the collaborators must match, because that's what justifies the pattern.

Further reading