On this page

Bridge

Bridge is the structural pattern people find hardest to explain, because its textbook definition sounds abstract and its code looks like plain composition. The structural patterns overview shows a short notification example. This page goes further. It starts from the class explosion that Bridge prevents, shows how to choose the line between the two hierarchies, and walks through a full implementation in three languages. It then covers where Bridge shows up in real platforms, and how to tell it apart from Strategy and Adapter, which have nearly the same shape.

Intent

Decouple an abstraction from its implementation so that the two can vary independently.

In plainer words: when a concept varies along two independent dimensions, don't model both dimensions with one inheritance tree. Give each dimension its own hierarchy, and let an object from the first hold a reference to an object from the second. That reference is the "bridge".

"Abstraction" and "implementation" here don't mean "interface" and "class that implements it". They mean two layers:

  • The abstraction is the high-level, client-facing side: what the thing is and what it does in domain terms. Examples are an invoice report, a playlist player or a shape on a canvas.
  • The implementation (or implementor) is the low-level, platform-facing side: the primitive operations the abstraction is built from. Examples are "write a heading in this output format", "play this audio buffer on this device" or "draw a line with this graphics API".

The abstraction's methods are written in terms of the implementor's primitives. Neither side knows the concrete classes on the other.

The problem

You're building the reporting module of a billing product. There are two reports, an invoice and a monthly usage summary. Customers can download each one as Markdown, plain text or HTML.

The first developer models this with inheritance, which seems natural: "an HTML invoice is a report".

import java.util.*;

record Line(String item, int qty, long unitCents) {}

abstract class Report {
    abstract String render();
    static String money(long cents) { return String.format("%d.%02d", cents / 100, cents % 100); }
}

class MarkdownInvoice extends Report {
    final String customer; final List<Line> lines;
    MarkdownInvoice(String customer, List<Line> lines) { this.customer = customer; this.lines = lines; }
    String render() {
        StringBuilder sb = new StringBuilder("# Invoice\n**Customer:** " + customer + "\n| Item | Qty | Amount |\n|---|---|---|\n");
        long total = 0;
        for (Line l : lines) {
            long amount = l.qty() * l.unitCents();
            total += amount;
            sb.append("| ").append(l.item()).append(" | ").append(l.qty()).append(" | ").append(money(amount)).append(" |\n");
        }
        return sb.append("**Total:** ").append(money(total)).toString();
    }
}

class HtmlInvoice extends Report {
    final String customer; final List<Line> lines;
    HtmlInvoice(String customer, List<Line> lines) { this.customer = customer; this.lines = lines; }
    String render() {
        StringBuilder sb = new StringBuilder("<h1>Invoice</h1><p><b>Customer:</b> " + customer + "</p><table>");
        long total = 0;                                           // the same totalling logic, copied
        for (Line l : lines) {
            long amount = l.qty() * l.unitCents();
            total += amount;
            sb.append("<tr><td>").append(l.item()).append("</td><td>").append(l.qty())
              .append("</td><td>").append(money(amount)).append("</td></tr>");
        }
        return sb.append("</table><p><b>Total:</b> ").append(money(total)).append("</p>").toString();
        // and nobody escaped the customer name
    }
}

// ... PlainTextInvoice, MarkdownUsage, HtmlUsage, PlainTextUsage: four more classes like these

class Demo {
    public static void main(String[] args) {
        List<Line> lines = List.of(new Line("Seats", 3, 1200), new Line("Storage", 1, 450));
        String md = new MarkdownInvoice("Acme", lines).render();
        String html = new HtmlInvoice("<script>x</script>", lines).render();
        assert md.endsWith("**Total:** 40.50");
        assert html.contains("<script>");                         // the XSS bug, present in one variant only
        System.out.println("before: 2 of 6 classes written, logic already duplicated");
    }
}

Count the classes. Two reports times three formats is six classes. Every new format adds one class per report, and every new report adds one class per format. Add a CSV format and a tax-summary report and you're at twelve. In general it's reports × formats, and that growth rate is the signature of the problem.

The count is the smaller issue. The bigger ones are:

  1. Logic is duplicated across one dimension. The invoice totalling loop lives in MarkdownInvoice, HtmlInvoice and PlainTextInvoice. When finance asks for tax lines, three classes change, and one will be missed.
  2. Formatting knowledge is duplicated across the other. How to write an HTML table, and that HTML needs escaping, lives in HtmlInvoice and HtmlUsage. The demo above shows the result: one HTML class escapes nothing, and an attacker-controlled customer name becomes a script tag.
  3. The choice is frozen at construction time. A MarkdownInvoice can never become HTML. If the format is a user preference that arrives at runtime, you end up with a factory switch that has to list all six combinations.
  4. Changes cut across files for the wrong reasons. A designer changing the HTML look edits invoice code, and a finance change edits formatting code.

The underlying mistake is using a single inheritance tree for two independent reasons to vary. Inheritance gives you one axis of variation per tree. When you need two, you get a cross-product.

Structure

Bridge splits the tree along the seam between the two dimensions. What a report contains becomes one hierarchy (the abstraction). How a document is written in a given format becomes another (the implementor). Each report holds a renderer.

classDiagram
    class Report {
        <<abstract>>
        #renderer: Renderer
        +Report(renderer: Renderer)
        +render() String
    }
    class InvoiceReport {
        -customer: String
        -lines: List
        +render() String
    }
    class UsageReport {
        -month: String
        -callsByEndpoint: Map
        +render() String
    }
    class Renderer {
        <<interface>>
        +title(text) String
        +field(label, value) String
        +table(headers, rows) String
    }
    class MarkdownRenderer {
        +title(text) String
        +field(label, value) String
        +table(headers, rows) String
    }
    class PlainTextRenderer {
        +title(text) String
        +field(label, value) String
        +table(headers, rows) String
    }
    class HtmlRenderer {
        +title(text) String
        +field(label, value) String
        +table(headers, rows) String
    }
    Report <|-- InvoiceReport
    Report <|-- UsageReport
    Report o--> Renderer : bridge
    Renderer <|.. MarkdownRenderer
    Renderer <|.. PlainTextRenderer
    Renderer <|.. HtmlRenderer

Now the class count is reports + formats: 2 + 3 = 5 instead of 6, and 3 + 4 = 7 instead of 12 after the next round of requirements. More importantly, each fact lives in one place. Invoice totalling is in InvoiceReport, and HTML escaping is in HtmlRenderer.

Rendering an invoice as HTML runs like this:

sequenceDiagram
    participant Client
    participant Inv as InvoiceReport
    participant R as HtmlRenderer
    Client->>Inv: render()
    Inv->>Inv: compute line amounts and total
    Inv->>R: title(Invoice INV-7)
    R-->>Inv: heading markup
    Inv->>R: field("Customer", name)
    R-->>Inv: escaped paragraph
    Inv->>R: table(headers, rows)
    R-->>Inv: escaped table markup
    Inv->>R: field("Total", "40.50")
    R-->>Inv: paragraph
    Inv-->>Client: joined document

Participants

ParticipantRole in the exampleResponsibility
AbstractionReportThe client-facing interface. Holds a reference to an implementor and builds its operations from the implementor's primitives.
Refined abstractionInvoiceReport, UsageReportVariants of the abstraction. Each adds its own domain logic (totals, sorting, highlights) and never mentions a concrete format.
ImplementorRendererThe interface for the low-level primitives: title, labelled field, table. It doesn't have to look like the abstraction's interface. Usually it's smaller and more primitive.
Concrete implementorMarkdownRenderer, PlainTextRenderer, HtmlRendererImplements the primitives for one platform or format, including that format's rules (escaping, alignment, syntax).
ClientDownload controllerPicks a report and a renderer, usually from runtime input, and joins them.

The most important design decision is the implementor interface. It should be a small set of primitives that every implementation can honour. It should not be a copy of the abstraction's methods. A Renderer with renderInvoice() and renderUsage() methods would just move the cross-product into the renderer: every new report would then need a method on every renderer.

A useful test is to imagine adding a new report. If it can be written using only the existing primitives, the line is in the right place. Then imagine adding a new format. If implementing the existing primitives is enough, without touching any report, the line is still right.

Implementation

The renderers below are stateless. Each primitive takes data and returns a string fragment, and the report joins the fragments. That's deliberate: a stateless implementor can be shared by any number of reports, across threads, with no surprises. An implementor that accumulates output in a field would work too, but then you can't share one renderer between two reports that render concurrently.

The HTML renderer escapes every piece of text it writes. Because the escaping lives in the one class that knows the output is HTML, no report can forget it.

import java.util.*;
import java.util.stream.*;

// ================= Implementor =================
interface Renderer {
    String title(String text);
    String field(String label, String value);
    String table(List<String> headers, List<List<String>> rows);
}

// ================= Concrete implementors =================
final class MarkdownRenderer implements Renderer {
    public String title(String text) { return "# " + text; }
    public String field(String label, String value) { return "**" + label + ":** " + value; }
    public String table(List<String> headers, List<List<String>> rows) {
        StringBuilder sb = new StringBuilder(row(headers)).append('\n')
            .append(headers.stream().map(h -> "---").collect(Collectors.joining("|", "|", "|")));
        for (List<String> r : rows) sb.append('\n').append(row(r));
        return sb.toString();
    }
    private static String row(List<String> cells) { return "| " + String.join(" | ", cells) + " |"; }
}

final class PlainTextRenderer implements Renderer {
    public String title(String text) { return text + "\n" + "=".repeat(text.length()); }
    public String field(String label, String value) { return label + ": " + value; }
    public String table(List<String> headers, List<List<String>> rows) {
        int[] width = new int[headers.size()];
        for (List<String> r : concat(headers, rows))
            for (int i = 0; i < r.size(); i++) width[i] = Math.max(width[i], r.get(i).length());
        return concat(headers, rows).stream()
            .map(r -> IntStream.range(0, r.size())
                .mapToObj(i -> String.format("%-" + width[i] + "s", r.get(i)))
                .collect(Collectors.joining("  ")).stripTrailing())
            .collect(Collectors.joining("\n"));
    }
    private static List<List<String>> concat(List<String> head, List<List<String>> rows) {
        List<List<String>> all = new ArrayList<>(); all.add(head); all.addAll(rows); return all;
    }
}

final class HtmlRenderer implements Renderer {
    static String esc(String s) {
        return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;");
    }
    public String title(String text) { return "<h1>" + esc(text) + "</h1>"; }
    public String field(String label, String value) { return "<p><b>" + esc(label) + ":</b> " + esc(value) + "</p>"; }
    public String table(List<String> headers, List<List<String>> rows) {
        StringBuilder sb = new StringBuilder("<table><tr>");
        headers.forEach(h -> sb.append("<th>").append(esc(h)).append("</th>"));
        sb.append("</tr>");
        for (List<String> r : rows) {
            sb.append("<tr>");
            r.forEach(c -> sb.append("<td>").append(esc(c)).append("</td>"));
            sb.append("</tr>");
        }
        return sb.append("</table>").toString();
    }
}

// ================= Abstraction =================
abstract class Report {
    protected final Renderer renderer;                     // the bridge
    Report(Renderer renderer) { this.renderer = Objects.requireNonNull(renderer); }
    abstract String render();
    static String money(long cents) { return String.format("%d.%02d", cents / 100, cents % 100); }
}

// ================= Refined abstractions =================
record Line(String item, int qty, long unitCents) {
    long amountCents() { return qty * unitCents; }
}

final class InvoiceReport extends Report {
    private final String number, customer;
    private final List<Line> lines;
    InvoiceReport(Renderer r, String number, String customer, List<Line> lines) {
        super(r); this.number = number; this.customer = customer; this.lines = List.copyOf(lines);
    }
    long totalCents() { return lines.stream().mapToLong(Line::amountCents).sum(); }
    String render() {
        List<List<String>> rows = lines.stream()
            .map(l -> List.of(l.item(), String.valueOf(l.qty()), money(l.amountCents()))).toList();
        return String.join("\n",
            renderer.title("Invoice " + number),
            renderer.field("Customer", customer),
            renderer.table(List.of("Item", "Qty", "Amount"), rows),
            renderer.field("Total", money(totalCents())));
    }
}

final class UsageReport extends Report {
    private final String month;
    private final Map<String, Integer> callsByEndpoint;
    UsageReport(Renderer r, String month, Map<String, Integer> callsByEndpoint) {
        super(r); this.month = month; this.callsByEndpoint = Map.copyOf(callsByEndpoint);
    }
    String render() {
        List<Map.Entry<String, Integer>> sorted = callsByEndpoint.entrySet().stream()
            .sorted(Map.Entry.<String, Integer>comparingByValue().reversed().thenComparing(Map.Entry.comparingByKey()))
            .toList();
        List<List<String>> rows = sorted.stream().map(e -> List.of(e.getKey(), String.valueOf(e.getValue()))).toList();
        return String.join("\n",
            renderer.title("Usage for " + month),
            renderer.table(List.of("Endpoint", "Calls"), rows),
            renderer.field("Busiest endpoint", sorted.isEmpty() ? "none" : sorted.get(0).getKey()));
    }
}

class Demo {
    public static void main(String[] args) {
        List<Line> lines = List.of(new Line("Seats", 3, 1200), new Line("Storage", 1, 450));

        String md = new InvoiceReport(new MarkdownRenderer(), "INV-7", "Acme", lines).render();
        assert md.equals("""
            # Invoice INV-7
            **Customer:** Acme
            | Item | Qty | Amount |
            |---|---|---|
            | Seats | 3 | 36.00 |
            | Storage | 1 | 4.50 |
            **Total:** 40.50""");

        String txt = new InvoiceReport(new PlainTextRenderer(), "INV-7", "Acme", lines).render();
        assert txt.equals("""
            Invoice INV-7
            =============
            Customer: Acme
            Item     Qty  Amount
            Seats    3    36.00
            Storage  1    4.50
            Total: 40.50""");

        // escaping lives in HtmlRenderer, so every report gets it for free
        String html = new InvoiceReport(new HtmlRenderer(), "INV-8", "<script>x</script>", lines).render();
        assert !html.contains("<script>") && html.contains("&lt;script&gt;");

        // the same renderer instance is shared by a different report
        Renderer shared = new MarkdownRenderer();
        String usage = new UsageReport(shared, "2026-10", Map.of("/search", 900, "/orders", 1200, "/login", 900)).render();
        assert usage.contains("| /orders | 1200 |\n| /login | 900 |\n| /search | 900 |");
        assert usage.endsWith("**Busiest endpoint:** /orders");

        // the format is a runtime choice, not a class name
        Map<String, Renderer> formats = Map.of("md", new MarkdownRenderer(), "txt", new PlainTextRenderer(), "html", new HtmlRenderer());
        for (String fmt : List.of("md", "txt", "html")) {
            String out = new InvoiceReport(formats.get(fmt), "INV-9", "Acme", lines).render();
            assert out.contains("40.50");
        }
        System.out.println("bridge: all checks passed");
    }
}
from abc import ABC, abstractmethod
from dataclasses import dataclass
from html import escape
from typing import Protocol


# ================= Implementor =================
class Renderer(Protocol):
    def title(self, text: str) -> str: ...
    def field(self, label: str, value: str) -> str: ...
    def table(self, headers: list[str], rows: list[list[str]]) -> str: ...


# ================= Concrete implementors =================
class MarkdownRenderer:
    def title(self, text: str) -> str:
        return f"# {text}"

    def field(self, label: str, value: str) -> str:
        return f"**{label}:** {value}"

    def table(self, headers: list[str], rows: list[list[str]]) -> str:
        def row(cells: list[str]) -> str:
            return "| " + " | ".join(cells) + " |"
        divider = "|" + "|".join("---" for _ in headers) + "|"
        return "\n".join([row(headers), divider, *(row(r) for r in rows)])


class PlainTextRenderer:
    def title(self, text: str) -> str:
        return f"{text}\n{'=' * len(text)}"

    def field(self, label: str, value: str) -> str:
        return f"{label}: {value}"

    def table(self, headers: list[str], rows: list[list[str]]) -> str:
        all_rows = [headers, *rows]
        widths = [max(len(r[i]) for r in all_rows) for i in range(len(headers))]
        return "\n".join("  ".join(c.ljust(w) for c, w in zip(r, widths)).rstrip() for r in all_rows)


class HtmlRenderer:
    def title(self, text: str) -> str:
        return f"<h1>{escape(text)}</h1>"

    def field(self, label: str, value: str) -> str:
        return f"<p><b>{escape(label)}:</b> {escape(value)}</p>"

    def table(self, headers: list[str], rows: list[list[str]]) -> str:
        head = "".join(f"<th>{escape(h)}</th>" for h in headers)
        body = "".join("<tr>" + "".join(f"<td>{escape(c)}</td>" for c in r) + "</tr>" for r in rows)
        return f"<table><tr>{head}</tr>{body}</table>"


# ================= Abstraction =================
class Report(ABC):
    def __init__(self, renderer: Renderer):
        self.renderer = renderer                           # the bridge

    @abstractmethod
    def render(self) -> str: ...

    @staticmethod
    def money(cents: int) -> str:
        return f"{cents // 100}.{cents % 100:02d}"


# ================= Refined abstractions =================
@dataclass(frozen=True)
class Line:
    item: str
    qty: int
    unit_cents: int

    @property
    def amount_cents(self) -> int:
        return self.qty * self.unit_cents


class InvoiceReport(Report):
    def __init__(self, renderer: Renderer, number: str, customer: str, lines: list[Line]):
        super().__init__(renderer)
        self.number, self.customer, self.lines = number, customer, list(lines)

    def total_cents(self) -> int:
        return sum(l.amount_cents for l in self.lines)

    def render(self) -> str:
        r = self.renderer
        rows = [[l.item, str(l.qty), self.money(l.amount_cents)] for l in self.lines]
        return "\n".join([
            r.title(f"Invoice {self.number}"),
            r.field("Customer", self.customer),
            r.table(["Item", "Qty", "Amount"], rows),
            r.field("Total", self.money(self.total_cents())),
        ])


class UsageReport(Report):
    def __init__(self, renderer: Renderer, month: str, calls_by_endpoint: dict[str, int]):
        super().__init__(renderer)
        self.month, self.calls = month, dict(calls_by_endpoint)

    def render(self) -> str:
        ranked = sorted(self.calls.items(), key=lambda kv: (-kv[1], kv[0]))
        r = self.renderer
        return "\n".join([
            r.title(f"Usage for {self.month}"),
            r.table(["Endpoint", "Calls"], [[k, str(v)] for k, v in ranked]),
            r.field("Busiest endpoint", ranked[0][0] if ranked else "none"),
        ])


lines = [Line("Seats", 3, 1200), Line("Storage", 1, 450)]

md = InvoiceReport(MarkdownRenderer(), "INV-7", "Acme", lines).render()
assert md == (
    "# Invoice INV-7\n**Customer:** Acme\n| Item | Qty | Amount |\n|---|---|---|\n"
    "| Seats | 3 | 36.00 |\n| Storage | 1 | 4.50 |\n**Total:** 40.50"
)

txt = InvoiceReport(PlainTextRenderer(), "INV-7", "Acme", lines).render()
assert txt == (
    "Invoice INV-7\n=============\nCustomer: Acme\n"
    "Item     Qty  Amount\nSeats    3    36.00\nStorage  1    4.50\nTotal: 40.50"
)

html = InvoiceReport(HtmlRenderer(), "INV-8", "<script>x</script>", lines).render()
assert "<script>" not in html and "&lt;script&gt;" in html

shared = MarkdownRenderer()
usage = UsageReport(shared, "2026-10", {"/search": 900, "/orders": 1200, "/login": 900}).render()
assert "| /orders | 1200 |\n| /login | 900 |\n| /search | 900 |" in usage
assert usage.endswith("**Busiest endpoint:** /orders")

formats: dict[str, Renderer] = {"md": MarkdownRenderer(), "txt": PlainTextRenderer(), "html": HtmlRenderer()}
for fmt in ("md", "txt", "html"):
    assert "40.50" in InvoiceReport(formats[fmt], "INV-9", "Acme", lines).render()
print("bridge: all checks passed")
import assert from "node:assert/strict";

// ================= Implementor =================
interface Renderer {
  title(text: string): string;
  field(label: string, value: string): string;
  table(headers: string[], rows: string[][]): string;
}

// ================= Concrete implementors =================
class MarkdownRenderer implements Renderer {
  title(text: string) { return `# ${text}`; }
  field(label: string, value: string) { return `**${label}:** ${value}`; }
  table(headers: string[], rows: string[][]) {
    const row = (cells: string[]) => `| ${cells.join(" | ")} |`;
    const divider = `|${headers.map(() => "---").join("|")}|`;
    return [row(headers), divider, ...rows.map(row)].join("\n");
  }
}

class PlainTextRenderer implements Renderer {
  title(text: string) { return `${text}\n${"=".repeat(text.length)}`; }
  field(label: string, value: string) { return `${label}: ${value}`; }
  table(headers: string[], rows: string[][]) {
    const all = [headers, ...rows];
    const widths = headers.map((_, i) => Math.max(...all.map((r) => r[i].length)));
    return all.map((r) => r.map((c, i) => c.padEnd(widths[i])).join("  ").trimEnd()).join("\n");
  }
}

class HtmlRenderer implements Renderer {
  static esc(s: string): string {
    return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
  }
  title(text: string) { return `<h1>${HtmlRenderer.esc(text)}</h1>`; }
  field(label: string, value: string) { return `<p><b>${HtmlRenderer.esc(label)}:</b> ${HtmlRenderer.esc(value)}</p>`; }
  table(headers: string[], rows: string[][]) {
    const head = headers.map((h) => `<th>${HtmlRenderer.esc(h)}</th>`).join("");
    const body = rows.map((r) => `<tr>${r.map((c) => `<td>${HtmlRenderer.esc(c)}</td>`).join("")}</tr>`).join("");
    return `<table><tr>${head}</tr>${body}</table>`;
  }
}

// ================= Abstraction =================
abstract class Report {
  constructor(protected readonly renderer: Renderer) {}     // the bridge
  abstract render(): string;
  static money(cents: number): string { return `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`; }
}

// ================= Refined abstractions =================
interface Line { item: string; qty: number; unitCents: number }

class InvoiceReport extends Report {
  constructor(renderer: Renderer, private readonly number: string,
              private readonly customer: string, private readonly lines: readonly Line[]) {
    super(renderer);
  }
  totalCents(): number { return this.lines.reduce((sum, l) => sum + l.qty * l.unitCents, 0); }
  render(): string {
    const rows = this.lines.map((l) => [l.item, String(l.qty), Report.money(l.qty * l.unitCents)]);
    return [
      this.renderer.title(`Invoice ${this.number}`),
      this.renderer.field("Customer", this.customer),
      this.renderer.table(["Item", "Qty", "Amount"], rows),
      this.renderer.field("Total", Report.money(this.totalCents())),
    ].join("\n");
  }
}

class UsageReport extends Report {
  constructor(renderer: Renderer, private readonly month: string,
              private readonly calls: ReadonlyMap<string, number>) {
    super(renderer);
  }
  render(): string {
    const ranked = [...this.calls].sort(([ka, va], [kb, vb]) => vb - va || ka.localeCompare(kb));
    return [
      this.renderer.title(`Usage for ${this.month}`),
      this.renderer.table(["Endpoint", "Calls"], ranked.map(([k, v]) => [k, String(v)])),
      this.renderer.field("Busiest endpoint", ranked.length ? ranked[0][0] : "none"),
    ].join("\n");
  }
}

const lines: Line[] = [{ item: "Seats", qty: 3, unitCents: 1200 }, { item: "Storage", qty: 1, unitCents: 450 }];

const md = new InvoiceReport(new MarkdownRenderer(), "INV-7", "Acme", lines).render();
assert.equal(md, "# Invoice INV-7\n**Customer:** Acme\n| Item | Qty | Amount |\n|---|---|---|\n" +
  "| Seats | 3 | 36.00 |\n| Storage | 1 | 4.50 |\n**Total:** 40.50");

const txt = new InvoiceReport(new PlainTextRenderer(), "INV-7", "Acme", lines).render();
assert.equal(txt, "Invoice INV-7\n=============\nCustomer: Acme\n" +
  "Item     Qty  Amount\nSeats    3    36.00\nStorage  1    4.50\nTotal: 40.50");

const html = new InvoiceReport(new HtmlRenderer(), "INV-8", "<script>x</script>", lines).render();
assert.ok(!html.includes("<script>") && html.includes("&lt;script&gt;"));

const shared = new MarkdownRenderer();
const usage = new UsageReport(shared, "2026-10", new Map([["/search", 900], ["/orders", 1200], ["/login", 900]])).render();
assert.ok(usage.includes("| /orders | 1200 |\n| /login | 900 |\n| /search | 900 |"));
assert.ok(usage.endsWith("**Busiest endpoint:** /orders"));

const formats: Record<string, Renderer> = { md: new MarkdownRenderer(), txt: new PlainTextRenderer(), html: new HtmlRenderer() };
for (const fmt of ["md", "txt", "html"]) {
  assert.ok(new InvoiceReport(formats[fmt], "INV-9", "Acme", lines).render().includes("40.50"));
}
console.log("bridge: all checks passed");

Growing each side independently

The payoff shows when requirements arrive, and each kind of change touches one side only.

  • A new format (CSV, say). Write CsvRenderer with three methods. title might return a comment line, field a two-cell row and table the rows with proper quoting. No report changes. Both existing reports, and every future one, can be exported as CSV.
  • A new report (a tax summary). Write TaxSummaryReport using title, field and table. No renderer changes. It's immediately available in every format.
  • A rule that belongs to one format. HTML needs escaping and Markdown needs | escaped inside table cells. Each rule goes in its renderer and applies to all reports.
  • A rule that belongs to one report. Invoices need tax lines. That's an InvoiceReport change, and it applies in all formats.

That's the Open/Closed Principle applied to two dimensions at once: each hierarchy is open for extension, and adding to one doesn't modify the other.

When the implementor needs a new primitive

Sometimes a new report needs something the implementor can't express, such as a bullet list or a chart. Then you add a primitive to Renderer, and every concrete renderer has to implement it. That's the one change that does cross the bridge, so make it carefully:

  • Add primitives that are general (bulletList(items)), not report-specific (renderTaxBreakdown(...)).
  • Where a sensible fallback exists, provide it once. A Java default method, a base class or a helper can express bulletList in terms of field so existing renderers keep working until they get a native version.
  • If you find you're adding a primitive for every new report, the line between the hierarchies is in the wrong place. The implementor has become a second copy of the abstraction.

Testing a bridge

The split makes testing simpler on both sides, because each hierarchy can be tested without the other's concrete classes.

  • Test reports with a recording renderer. A tiny fake Renderer that returns tagged strings, such as field(Total=40.50), lets you check that InvoiceReport computes the right total and asks for the right primitives in the right order. You check the report's logic without parsing HTML or Markdown.
  • Test renderers with plain data. Feed HtmlRenderer.table a cell containing <, & and quotes and check the escaping. Feed PlainTextRenderer.table cells of different widths and check the alignment. No report is involved.
  • Keep a few end-to-end snapshots. One or two full outputs per format, like the exact-string asserts in the demos, catch mistakes in how the two halves fit together, such as a missing newline between fragments.

This is the same benefit you get from any interface boundary, but it matters more here. Without the split, testing every format of every report means testing the whole cross-product. With it, you test m reports and n renderers separately, plus a handful of combinations.

Choosing and joining the pair

Someone has to decide which renderer goes with which report. Keep that decision at the edge of the system, in a controller, a small factory or your dependency injection setup, not inside the reports. A map from format name to renderer, as in the demos, is usually enough. If the implementors come in families that must match (a Windows button renderer with a Windows menu renderer), an Abstract Factory that hands out a consistent set is the classic companion to Bridge.

Bridge with only one side varying

You'll often see a "bridge" where the abstraction side has no subclasses at all: one Report class holding a Renderer. That's fine, and it's still useful, because the implementor side varies and the abstraction doesn't depend on any concrete platform. Strictly speaking it's closer to plain composition or Strategy, and you don't need to argue about the label. The full pattern earns its name when both sides have, or are expected to have, several variants.

Real-world uses

  • JDBC. Application code is written against the java.sql interfaces (Connection, Statement, ResultSet), and the DriverManager hands back connections from whichever java.sql.Driver is registered for the URL. Vendors supply drivers for their databases. The API your code uses and the database-specific implementation underneath evolve separately, which is why JDBC is a common textbook example of Bridge. The fit isn't exact, because the driver implements the API interfaces directly instead of there being a separate abstraction hierarchy above it, but the decoupling of "what the application asks for" from "how this vendor does it" is the Bridge idea.
  • SLF4J. Libraries log through the SLF4J API (org.slf4j.Logger). At deployment time a single provider (Logback, a Log4j 2 binding, a java.util.logging binding or a no-op) does the actual work. The logging calls in thousands of libraries and the logging backend chosen by each application vary independently. That's the main reason the split exists.
  • java.util.logging and Python's logging. In both, a Logger (what to log, at which level, from which component) sends records to Handlers (where they go: console, file, socket), and each handler has a Formatter (how a record looks). Destination and format are separate hierarchies you combine freely, so a new handler works with every formatter.
  • AWT peers (historically). Early AWT components such as java.awt.Button delegated their native behaviour to a platform-specific peer object (a ComponentPeer implementation for Windows, Motif and so on). The component hierarchy and the per-platform peer hierarchy varied independently. This is the textbook GUI-toolkit case. Peers are an internal detail and were never meant for application code.
  • React renderers. React's reconciler, which works out what changed in the component tree, is shared. Separate renderers such as React DOM, React Native and the test renderer supply the host-specific operations (create a DOM node, create a native view). Components are written once against React's API, and the host platform is a separate, swappable layer.
  • Device drivers and OS abstraction layers follow the same idea at a larger scale. A filesystem talks to a block-device interface, and each driver implements it for one kind of hardware.

When NOT to use it

When only one dimension varies. If you have three report types and they'll only ever be HTML, a Renderer interface is speculative. Write the reports, keep the HTML helpers in one place, and introduce the split when a second format is actually requested. Extracting a renderer later is a mechanical refactor: the primitives are already there as helper methods. Building two hierarchies for a cross-product of 3 × 1 is a textbook case of over-patterning.

When the dimensions aren't independent. Bridge assumes any abstraction can pair with any implementor. If the pairs are constrained (the usage report only makes sense in CSV, the invoice can never be plain text), you'll end up with type checks and "unsupported" exceptions inside the hierarchies. Then either the dimensions are really one dimension, or you need something that expresses the constraints, such as an explicit registry of supported pairs.

When you can't find a stable primitive interface. The pattern only pays off if the implementor interface is small and stays stable. If each new abstraction needs new primitives, every change crosses the bridge and you've doubled the number of classes to edit. Sometimes the honest answer is that the formats are too different to share primitives. A PDF invoice with a precise layout and a CSV invoice have little in common beyond the data. Then separate "build the data model" from "write it out in format X" with a plain function per format, and skip the abstraction hierarchy.

When a function parameter is enough. In Python and TypeScript, an implementor with one method is just a function. render(report, escape=html.escape) doesn't need a class hierarchy.

The costs, even when it's right: two hierarchies to understand instead of one, an extra indirection on every primitive call, and a design decision (where the line goes) that's expensive to get wrong. Readers new to the code also have to learn that "the HTML part of the invoice" isn't in the invoice class. Good names (Renderer, HtmlRenderer) carry most of that explanation.

PatternSame shape?How it differs from Bridge
StrategyYes: context holds an interface, concrete classes implement itStrategy swaps one algorithm used by a context, often at runtime, and the context usually has no hierarchy of its own. Bridge separates two whole hierarchies where the implementor is a platform of primitives that the abstraction's methods are built from. Ask which question the design answers. "Which way should I compute this?" is Strategy. "On what platform do these concepts run?" is Bridge.
AdapterYes: wrapper holds a delegateAdapter is applied after the fact to make an existing, incompatible class fit an interface. Bridge is designed up front so that two sides can evolve separately. The bridge's implementor interface is one you design, while an adapter's adaptee interface is one you're stuck with. In practice they combine well: to support a third-party PDF library as a renderer, write an adapter that implements Renderer on top of it.
Abstract FactoryNoCreates matching families of implementors (all the Windows peers, all the HTML renderers) so that a bridge gets a consistent set.
DecoratorPartlyDecorator wraps an object with the same interface to add behaviour. Bridge connects objects with different interfaces at different levels.
Template MethodNoFixes an algorithm's skeleton in a base class and lets subclasses fill in steps, which is variation by inheritance along one axis. Bridge gets the same effect through composition, and makes the second axis swappable at runtime. A refined abstraction often uses a template method internally.

Structurally, Strategy, Bridge and an object Adapter can produce identical class diagrams. The pattern name describes intent, and that's what you should explain in an interview. "These report classes hold a renderer so formats and report types can vary independently" tells the interviewer far more than "this is the Bridge pattern".

The smell that suggests it

  • Class names that are cross-products. HtmlInvoice, PdfInvoice, HtmlStatement, PdfStatement. Or WindowsButton, MacButton, WindowsCheckbox, MacCheckbox. Or EmailUrgentAlert, SmsUrgentAlert, EmailDigestAlert. Two words in each name, each drawn from a small set, means two dimensions modelled as one.
  • Subclass counts that multiply. Adding one variant on one axis forces you to add several classes.
  • The same logic in sibling classes along one axis, and the same platform code in sibling classes along the other. In the "before" example, totalling is copied across formats, and HTML table markup is copied across reports.
  • A switch over a platform or format inside domain methods. if (format == HTML) ... else if (format == MARKDOWN) repeated in every report method is the cross-product in procedural form.
  • "We can't change the format after creation" when the format is really a runtime choice, such as a user preference, an Accept header or a feature flag.

The refactoring goes in four steps. Find the two axes. Identify the primitive operations one axis needs from the other. Extract those primitives into an implementor interface with one class per variant. Collapse the cross-product subclasses into one class per variant on the abstraction side, each holding an implementor.

Interview questions

  1. "Explain Bridge in one sentence." When a concept varies along two independent dimensions, give each dimension its own hierarchy and let one hold a reference to the other, so you get m + n classes instead of m × n, and either side can change without touching the other.

  2. "What do 'abstraction' and 'implementation' mean in Bridge? Isn't every interface an abstraction?" They're layers, not Java keywords. The abstraction is the high-level, domain-facing side, such as a report or a shape. The implementor is the low-level, platform-facing side, which provides the primitives the abstraction is built from, such as "write a table" or "draw a line". The abstraction can be an abstract class with subclasses, and the implementor is usually an interface with several implementations.

  3. "How is Bridge different from Strategy? The diagrams look the same." The structure is the same. The intent differs. Strategy picks one interchangeable algorithm for a context. Bridge separates two hierarchies so both can grow, and the implementor is a set of primitives the abstraction's operations are composed from. Strategy is usually about how to do one task. Bridge is about which platform the whole concept runs on.

  4. "And from Adapter?" Adapter is a retrofit: it makes an existing class with the wrong interface fit the one you need. Bridge is designed up front, and you control both sides' interfaces. They often appear together, because an adapter is how you plug a third-party library in as a concrete implementor.

  5. "How do you decide what goes in the implementor interface?" Make it the smallest set of primitives that every implementation can honour and that the abstractions can be built from. Check it by imagining a new abstraction (it should need no new primitives) and a new implementor (it should need to implement only those primitives). If the implementor starts getting one method per abstraction, the line is in the wrong place.

  6. "Model notifications that can be urgent, normal or digest, sent by email, SMS or push." Urgency is the abstraction: UrgentNotification retries and escalates, and DigestNotification batches. The channel is the implementor, with primitives like send(recipient, subject, body) and maxLength(). Each notification holds a channel. Adding WhatsApp is one class, and adding a "scheduled" notification type is one class. I'd also mention which pairs are invalid (a digest over SMS might exceed length limits) and handle that with maxLength() rather than type checks.

  7. "Should the implementor be stateful?" Prefer stateless, returning results rather than accumulating them, so one implementor instance can be shared by many abstractions and across threads. If it must hold state, such as a connection or an open file, make ownership explicit: either each abstraction gets its own instance, or access is synchronised.

  8. "Where have you seen Bridge in real libraries?" SLF4J is the clearest: libraries code against the logging API and the application picks one backend. JDBC is the classic textbook example, with the java.sql API on one side and vendor drivers on the other. Logging frameworks also bridge handlers (where output goes) with formatters (what it looks like).

  9. "When would you not use Bridge?" When only one dimension actually varies today, I'd keep a single hierarchy and extract the implementor when a second variant is requested. I'd also avoid it when the dimensions aren't truly independent, or when no stable primitive interface exists between them.

  10. "What happens when a new abstraction needs a primitive the implementor doesn't have?" It's the one change that crosses the bridge. I'd add a general-purpose primitive, give it a default implementation in terms of existing primitives where that's sensible, and then specialise it in the implementors that can do better. If that keeps happening, I'd revisit where the line between the hierarchies is drawn.