LOW-LEVEL DESIGN · STRUCTURAL PATTERNS · STRUCTURAL · 28 OF 48

Bridge Design Pattern in Java: Stop the Subclass Explosion

The Bridge pattern explained with shop documents (invoice, packing slip, gift note) printed through different renderers (HTML, receipt printer, Markdown): spotting two dimensions that vary independently, the abstraction and implementation hierarchies joined by composition, m plus n classes instead of m times n, switching at runtime, and Bridge vs Strategy and Adapter.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 16

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 199 lines, with a small main() demo. Save it as ReceiptBridgeDemo.java, then run javac ReceiptBridgeDemo.java && java ReceiptBridgeDemo.

// Bridge pattern: documents (WHAT to print) and renderers (HOW to print) vary independently.
import java.util.List;
import java.util.Locale;

public class ReceiptBridgeDemo {

    public static void main(String[] args) {
        System.out.println("-- Before: one subclass per document AND format --");
        System.out.print(new InvoiceAsHtml("INV-31", 900).print());
        System.out.println("3 documents x 3 formats would need " + 3 * 3 + " classes");

        System.out.println("-- After: documents hold a renderer (the bridge) --");
        List<LineItem> items = List.of(new LineItem("Desk lamp", 2, 450), new LineItem("Bulb", 4, 60));
        PageRenderer html = new HtmlRenderer();
        PageRenderer thermal = new ThermalRenderer(32);
        PageRenderer markdown = new MarkdownRenderer();

        List<PrintableDoc> docs = List.of(
                new Invoice(html, "INV-31", items),
                new Invoice(thermal, "INV-31", items),          // same class, other format
                new PackingSlip(thermal, "INV-31", "B4", 2),
                new GiftNote(markdown, "Happy housewarming!"));
        for (PrintableDoc doc : docs) {
            System.out.println(doc.print());
        }
        System.out.println("3 documents + 3 renderers = " + (3 + 3) + " classes");
    }
}

// ---------------------------------------------------------------------------
// The problem: format code is copied into every document subclass.
// ---------------------------------------------------------------------------
class InvoiceAsHtml {
    private final String id;
    private final int total;

    InvoiceAsHtml(String id, int total) {
        this.id = id;
        this.total = total;
    }

    String print() {
        return "<h2>Invoice " + id + "</h2>\n<p><b>Total</b> " + total + "</p>\n";
    }
}
// ...and InvoiceAsThermal, SlipAsHtml, SlipAsThermal, GiftNoteAsMarkdown...

// ---------------------------------------------------------------------------
// Implementation side: primitive operations that know nothing about invoices.
// ---------------------------------------------------------------------------
interface PageRenderer {
    String heading(String text);

    String row(String label, String value);

    String divider();
}

class HtmlRenderer implements PageRenderer {
    @Override
    public String heading(String text) {
        return "<h2>" + text + "</h2>\n";
    }

    @Override
    public String row(String label, String value) {
        return "<p><b>" + label + "</b> " + value + "</p>\n";
    }

    @Override
    public String divider() {
        return "<hr>\n";
    }
}

/** A narrow receipt printer: fixed width, upper-case centred heading, padded rows. */
class ThermalRenderer implements PageRenderer {
    private final int width;

    ThermalRenderer(int width) {
        this.width = width;
    }

    @Override
    public String heading(String text) {
        String upper = text.toUpperCase(Locale.ROOT);
        int pad = Math.max(0, (width - upper.length()) / 2);
        return " ".repeat(pad) + upper + "\n";
    }

    @Override
    public String row(String label, String value) {
        int room = Math.max(1, width - value.length() - 1);
        String left = label.length() > room ? label.substring(0, room) : label;
        return left + " ".repeat(Math.max(1, width - left.length() - value.length())) + value + "\n";
    }

    @Override
    public String divider() {
        return "-".repeat(width) + "\n";
    }
}

/** Added later: one class, and every document can use it immediately. */
class MarkdownRenderer implements PageRenderer {
    @Override
    public String heading(String text) {
        return "## " + text + "\n";
    }

    @Override
    public String row(String label, String value) {
        return "- **" + label + "**: " + value + "\n";
    }

    @Override
    public String divider() {
        return "---\n";
    }
}

// ---------------------------------------------------------------------------
// Abstraction side: WHAT goes on the page, written only with primitives.
// ---------------------------------------------------------------------------
abstract class PrintableDoc {
    protected final PageRenderer renderer;   // the bridge

    protected PrintableDoc(PageRenderer renderer) {
        this.renderer = renderer;
    }

    abstract String print();
}

record LineItem(String name, int qty, int unitPrice) {
    int amount() {
        return qty * unitPrice;
    }
}

class Invoice extends PrintableDoc {
    private final String id;
    private final List<LineItem> items;

    Invoice(PageRenderer renderer, String id, List<LineItem> items) {
        super(renderer);
        this.id = id;
        this.items = List.copyOf(items);
    }

    @Override
    String print() {
        StringBuilder out = new StringBuilder(renderer.heading("Invoice " + id));
        int total = 0;
        for (LineItem item : items) {
            out.append(renderer.row(item.name() + " x" + item.qty(), String.valueOf(item.amount())));
            total += item.amount();
        }
        out.append(renderer.divider());
        out.append(renderer.row("Total", String.valueOf(total)));
        return out.toString();
    }
}

class PackingSlip extends PrintableDoc {
    private final String orderId;
    private final String bin;
    private final int boxes;

    PackingSlip(PageRenderer renderer, String orderId, String bin, int boxes) {
        super(renderer);
        this.orderId = orderId;
        this.bin = bin;
        this.boxes = boxes;
    }

    @Override
    String print() {
        return renderer.heading("Packing slip " + orderId)
                + renderer.row("Pick from bin", bin)
                + renderer.row("Boxes", String.valueOf(boxes))
                + renderer.divider();
    }
}

/** Added later: one class, and it prints through every renderer. */
class GiftNote extends PrintableDoc {
    private final String message;

    GiftNote(PageRenderer renderer, String message) {
        super(renderer);
        this.message = message;
    }

    @Override
    String print() {
        return renderer.heading("A gift for you") + renderer.row("Message", message) + renderer.divider();
    }
}

Notes

The problem

An online shop prints an invoice and a packing slip. Some go to a web page as HTML, some to a small receipt printer at the warehouse. The first design uses one subclass per pair: invoice as HTML, invoice as thermal, slip as HTML, slip as thermal. Add Markdown and you need two more. Add a gift note and you need three more. Three documents and three formats means nine classes, with formatting code copied everywhere.

One subclass per pair
  • InvoiceAsHtml
  • InvoiceAsThermal
  • SlipAsHtml
  • SlipAsThermal
  • add Markdown: +2 classes
  • add GiftNote: +3 classes
  • 3 docs x 3 formats = 9
  • and the HTML tags are copied
  • into every ...AsHtml class

Two dimensions

Look closer and there are two separate questions mixed into each class. What to print: an invoice has line items and a total, a slip has a bin and a box count. And how to print: HTML tags, a narrow thirty two column receipt, or Markdown. These change for different reasons, often by different teams. When one class mixes two independent reasons to change, inheritance alone multiplies them.

Find the two axes
  • axis 1: WHAT to print
  • invoice, packing slip,
  • gift note
  • axis 2: HOW to print
  • HTML, receipt printer,
  • Markdown
  • they change for different
  • reasons and different teams

The idea

The idea: split one hierarchy into two, and connect them with a field instead of inheritance. Formally, bridge decouples an abstraction from its implementation so the two can vary independently. The abstraction is the high level thing the client works with, here a printable document. The implementation is the set of low level operations it delegates to, here a page renderer. That field holding the renderer is the bridge.

Bridge in one line
  • split one hierarchy into two
  • abstraction: the high-level
  • thing the client uses
  • implementation: low-level
  • operations it delegates to
  • join them with a field
  • (composition), not extends
  • note: "implementation" here
  • is a role, not the keyword

The roles

Here are the roles with our names. On the left, the abstraction side: the printable document abstract class, and its refined abstractions, invoice and packing slip. On the right, the implementation side: the page renderer interface, with HTML renderer and thermal renderer. The order desk is the client. The only connection between the two sides is the renderer field inside printable document.

Implementor

Start with the implementation side. The page renderer interface has three primitive operations: a heading, a row with a label and a value, and a divider. The HTML renderer wraps them in tags. The thermal renderer centres an upper case heading, pads each row to exactly thirty two characters with the value on the right, and draws dashes. Neither renderer knows what an invoice or a slip is.

PageRenderer
interface PageRenderer {
    String heading(String text);
    String row(String label, String value);
    String divider();
}

class HtmlRenderer: <h2>, <p>, <hr>
class ThermalRenderer(int width):
  UPPERCASE heading, centred,
  label ....... value, ----

Abstraction

Now the abstraction side. Printable document is an abstract class that receives a renderer in its constructor and keeps it in a protected final field. Each refined abstraction writes its own print method using only those primitives. The invoice asks for a heading, then one row per line item, a divider and a total row. The packing slip asks for different rows. Neither of them contains a single HTML tag.

PrintableDoc and Invoice
abstract class PrintableDoc {
    protected final PageRenderer renderer;
    abstract String print();
}
class Invoice extends PrintableDoc {
    String print() {
        out += renderer.heading("Invoice")
        for each item: renderer.row(...)
        out += renderer.row("Total", t);
    }
}

One call

Follow one call. The order desk asks an invoice, built with the thermal renderer, to print. The invoice decides what goes on the page and calls heading with the invoice number, then row for desk lamp times two at nine hundred, and so on. The thermal renderer decides how each piece looks. The desk gets back a receipt ready for a thirty two column printer, without knowing which renderer was used.

m + n, not m x n

Now growth is easy. A gift note is one new class on the left, and it prints through every existing renderer for free. Markdown is one new class on the right, and every document can use it at once. Three documents and three formats is six classes instead of nine. Five documents and four formats is nine instead of twenty. And each output format now lives in exactly one place.

Growth
  • before: docs x formats
  • 3 x 3 = 9 classes
  • after: docs + formats
  • 3 + 3 = 6 classes
  • 5 docs, 4 formats:
  • 20 vs 9
  • and each format lives in
  • exactly one place

Choose at runtime

Because the link is a field, not a parent class, the choice happens at runtime. The order desk picks a thermal renderer when a receipt printer is attached and an HTML renderer for the web, then passes it into the same invoice class. In a real system the renderer usually comes from configuration or dependency injection. Testing is easy too: a renderer that records the calls checks the invoice logic with no printer.

Wiring
PageRenderer r = printerAttached
    ? new ThermalRenderer(32)
    : new HtmlRenderer();
new Invoice(r, "INV-31", items).print();

same Invoice class,
two very different outputs

When to use it

Use bridge when you can name two dimensions that truly vary on their own, and the code already shows it: class names like invoice as HTML or report for mobile. It also fits when the platform side must be swapped at runtime. Avoid it when only one axis varies or there is a single implementation. Then the extra interface is pure ceremony. Bridge is usually designed up front, or reached by refactoring a growing hierarchy.

Use / avoid
  • use when:
  • • two dimensions really vary
  • independently
  • • you see names like
  • XAsY, XForY, XOnY
  • • the platform side must be
  • swapped at runtime
  • avoid when:
  • • only one axis varies
  • • there is one implementation

Neighbours

In code, bridge looks a lot like strategy: an object holds an interface and delegates to it. The difference is intent and scale. Strategy swaps one algorithm inside one class. Bridge keeps two whole hierarchies growing side by side. Compared with adapter, an adapter fixes a mismatch between classes that already exist, while bridge separates things on purpose before they multiply. An abstract factory is often used to create the matching implementor.

Bridge compared
  • Strategy: one algorithm is
  • swappable inside one class
  • Bridge: a whole hierarchy
  • sits on top of another one,
  • both are extended
  • Adapter: fixes a mismatch
  • AFTER the fact
  • Bridge: separates on purpose
  • BEFORE things multiply
  • Abstract Factory can build
  • the matching implementor

In Java

The idea appears in JDBC, which is often described as a bridge. Your code talks to connection, statement and result set interfaces, and each database vendor ships a driver that implements them. You can switch from one database to another by changing the driver and the connection string, and the API and the drivers are developed by different groups on different schedules. That separation is exactly what the pattern is about.

A well-known example
  • JDBC: your code uses the
  • Connection, Statement and
  • ResultSet interfaces
  • each database driver supplies
  • the implementation
  • swap the driver: your code
  • does not change. The API and
  • the drivers evolve separately

In LLD interviews

In interviews, listen for two lists joined by the word and. Alert types and channels in a notification system. Payment types and processors. Vehicles and engine kinds. Reports and export formats. A common mistake is giving the implementor high level methods like render invoice, which drags the first axis into the second and brings the explosion back. Keep implementor methods primitive, and do not call every interface a bridge.

Where it shows up
  • notifications: alert type
  • x channel (SMS, email, push)
  • payments: payment type
  • x processor
  • vehicles: vehicle x engine
  • reports: report x exporter
  • mistakes:
  • • implementor too high level
  • (renderInvoice) leaks axis 1
  • • calling any interface bridge

Say it like this

How to say it. Documents and output formats vary independently, so I split them into two hierarchies. Printable document holds a page renderer, and documents are written only in terms of its primitive operations. A new document or a new format is one class each, so we get m plus n classes instead of m times n, and the renderer is chosen at runtime from configuration.

In the interview
  • "Documents and output formats
  • vary independently, so I split
  • them: PrintableDoc holds a
  • PageRenderer. New documents
  • and new formats are one class
  • each, m plus n instead of m
  • times n, and the renderer is
  • chosen at runtime."

Interview questions

What problem does the Bridge pattern solve?

It prevents a class explosion when a hierarchy varies along two independent dimensions. Instead of one subclass for every combination, you create two hierarchies, an abstraction and an implementation, and connect them with composition so each can be extended separately.

What do abstraction and implementation mean in Bridge?

The abstraction is the high-level interface the client uses, such as a document that can print itself. The implementation is a separate interface of lower-level operations it delegates to, such as a renderer with heading, row and divider. Implementation here is a role, not the Java implements keyword.

How is Bridge different from Strategy?

The structure is similar because both delegate to an interface held in a field. Strategy swaps one algorithm inside one context class. Bridge keeps two whole hierarchies evolving independently, and both sides are expected to gain new subclasses.

How is Bridge different from Adapter?

Adapter is applied after the fact to make an existing class fit an interface it was not designed for. Bridge is a deliberate design decision, made up front or during refactoring, to keep two dimensions apart before the combinations multiply.

How many classes does Bridge save?

With m variants of the abstraction and n implementations, plain inheritance needs about m times n classes, while Bridge needs about m plus n. For example 5 document types and 4 formats is 20 classes versus 9.

What is a common mistake when applying Bridge?

Giving the implementor high-level methods tied to specific abstractions, like renderInvoice. That leaks the first dimension into the second and brings back the explosion. Implementor methods should be primitive operations that any abstraction can combine.

Where is the Bridge idea seen in Java?

JDBC is a well-known example: application code depends on interfaces such as Connection and Statement, and each database driver provides the implementation. The API and drivers evolve separately and the driver can be swapped without changing application code.

Which LLD interview problems suit Bridge?

Problems with two independent lists: notification type and delivery channel, payment type and processor, vehicle and engine, report and export format. Name both axes, then show that adding to either one is a single new class.