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