Pattern 17/22 · Structural
Bridge
Split a class that carries two independent axes of change into two separate hierarchies joined by composition (one side holds an interface reference to the other), so either side can gain new members without touching the other.
01 — It starts with code that is breaking
Problem
The notification feature starts out simple: a Notification class with send(). Next week the PM asks "can it go out over SMS too?", so you add SmsNotification extends Notification. The week after: "email needs HTML", so you add EmailHtmlNotification. Six months later the notifications/ folder holds AlertEmailHtmlNotification, AlertSmsTextNotification, DigestEmailMarkdownNotification, plus a notification-factory.ts whose if/else tree is longer than all those classes combined.
Nobody did anything wrong. extends was the only tool on hand, so every combination became a class. But look closely at the names: each one is the product of two nouns — the kind of notification (Alert, Digest) and the delivery method (Email/HTML, SMS/text). Those two nouns change for different reasons, driven by different people, on different schedules.
The numbers say it plainly: 2 kinds × 3 channels × 3 formats = 18 classes. Adding a PDF format isn't "add one file", it's +6 classes, and the HTML rendering you wrote in AlertEmailHtmlNotification has to be copied into DigestEmailHtmlNotification, because those two classes share no parent that could hold the HTML.
And it breaks in very specific ways as the project grows: fixing one HTML formatting bug means editing 6 files; two teams open different ...Notification.ts files for two unrelated features and then collide in the same constructor at merge time; you can't test "HTML rendering" without also standing up a channel and a notification kind; and "pick the channel from tenant config" turns into a class-building switch — meaning the code has to guess which combinations exist.
You'll see the exact same shape elsewhere: PgDatabase, MysqlDatabase, PgQueryLoggingDatabase; ModalDesktopDark, ModalMobileLight; ExportCsvPg, ExportJsonMysql; or a UI button whose variants are variant × size × state × theme. The problem isn't "too many classes" — it's two (or three) independent axes of change welded into one by extends.
02 — The idea, before touching code
Solution
Bridge: pick one axis and move it into composition. That axis becomes an interface (GoF calls it the Implementor), and the class on the other axis holds a reference to that interface instead of extends-ing it. AlertNotification is not "an Email"; it has a channel and calls channel.deliver(...) at the right moment.
The whole value of the pattern is arithmetic: 2 + 3 + 3 = 8 instead of 18, and when you need PDF you add exactly one renderer object without touching a single notification class. The two axes live independently: tested independently, owned by different people, and every combination works — including ones nobody has thought of yet — because there's no combination class to forget to write.
In TypeScript, the "class hierarchy" on the implementor side usually shrinks to one interface plus a few object literals, so the real thing is much lighter than the GoF diagram. If the abstraction side doesn't branch either, your Bridge is just "a constructor that takes a dependency". You've written Bridge many times already, you just never named it — and never drew the class matrix to see how much it's worth.
03 — Doing it for real, one code fragment per step
Step by step
Name the two axes: what changes, and who changes it
Before touching code, list every existing class and split each name into nouns. For DigestEmailHtmlNotification: Digest (business), Email (delivery technology), Html (presentation format).
Each noun is an axis if it answers two questions: who asks for changes to it (product or platform team?) and does it change independently of the other nouns? If you sometimes change the channel without changing the format, and vice versa, those are two real axes, not two implementation details.
Notification (business) x Channel (technology) x Format (presentation)
Alert, Digest Email, SMS, Zalo text, HTML, Markdown
Database (business) x Vendor (backend)
SqlDatabase, MongoDatabase Postgres, MySQL, SQLite
Device (business) x Driver (manufacturer)
Tv, Radio Sony, LG, PhilipsWrite the inheritance version and count the classes it demands
Don't rush the refactor. Write the version "everyone writes the first time" and count — a number convinces a reviewer faster than any theory.
abstract class Notification {
abstract send(to: string, text: string): string
}
// The channel axis + format axis are crammed into the business axis's class hierarchy:
class AlertEmailText extends Notification {
send(to: string, text: string) { return 'SMTP ' + to + ' :: ' + text }
}
class AlertEmailHtml extends Notification {
send(to: string, text: string) { return 'SMTP ' + to + ' :: <p>' + text + '</p>' }
}
class AlertSmsText extends Notification {
send(to: string, text: string) { return 'SMS ' + to + ' :: ' + text }
}
class DigestEmailHtml extends Notification {
send(to: string, text: string) { return 'SMTP ' + to + ' :: <p>Digest: ' + text + '</p>' }
}
// ... plus DigestEmailText, DigestSmsText, and three Zalo ones nobody has written yetAlertEmailHtml and DigestEmailHtml is 90% identical — and there's no shared place to put it.Draw the class matrix before touching code
Draw a grid: rows are the business axis, columns are the implementor axis. Every cell is a class you have to write, test and maintain. This is what you hand the reviewer, not UML.
The refactor goal is now precisely defined: number of cells becomes rows plus columns. Write down today's number so you can compare at the end.
BEFORE (inheritance): AFTER (bridge):
text html md Alert \
Alert 1 1 1 = 6 Digest >-- Channel (email|sms|zalo)
Digest 1 1 1 (2 classes) /
Zalo/Email/SMS each x3 + Renderer (text|html|md)
6 classes today. +PDF -> 9 classes. +Webhook -> 12.
Bridge: 2 + 3 + 3 = 8 objects. +PDF -> 9. +Webhook -> 10.Pin down the interface for the implementation axis
Make the Implementor the axis that changes because of vendor / technology / format: Channel, Renderer, Driver. It must be written in the abstraction's language, not the vendor's.
That means deliver(to, body), not createTransport(options) — the interface is born from the caller. If you copy nodemailer's API verbatim as your interface, Bridge isn't working yet: the abstraction still "knows" about SMTP, and swapping in SMS for that Driver makes no sense. Where the vendor API doesn't fit, that's Adapter's job (sitting behind the Implementor).
/** Axis 2a: how it gets sent. The contract is defined by Notification. */
export interface Channel {
readonly id: string
deliver(to: string, body: string): string
}
/** Axis 2b: how it's presented. Completely independent of the channel. */
export interface Renderer {
readonly id: string
render(text: string): string
}The abstraction holds a reference instead of extending
The abstraction class has one job left: run the business flow and delegate. It doesn't new any channel, and doesn't compare channel.id === ... anywhere.
protected because subclasses on the same axis will reuse it; if the abstraction has no subclasses, make it private and don't abstract any further.
import type { Channel, Renderer } from './implementor'
export class Notification {
constructor(
protected channel: Channel,
protected renderer: Renderer,
) {}
/** Shared flow: format first, then send. */
send(to: string, text: string): string {
return this.channel.deliver(to, this.renderer.render(text))
}
}if (channel === ...). The abstraction's line count stays flat as the number of channels grows.protected channel: Channel, turns multiplication into addition.Implement both sides: business classes and implementor objects
The abstraction axis is still allowed to branch — Bridge forbids nothing there. AlertNotification adds a prefix, DigestNotification changes the heading, both call super.send() and both are blind to the channel.
The implementor side is the opposite: TypeScript checks structure, so an object literal matching Channel is already a valid implementor — no implements, no class. Each vendor's driver lives in its own file, even if that file is only 6 lines. It's also the only place allowed to import the vendor SDK (nodemailer, axios, Zalo OA...); the rest of the codebase never sees them.
Quick test for both files: on the business axis, no name like Email or Sms may appear; on the implementor axis, no name like Alert or Digest may appear. If one does, one of the axes is still leaking.
import { Notification } from './notification-v2'
import type { Channel, Renderer } from './implementor'
// --- axis 1: business, branch freely ---
export class AlertNotification extends Notification {
send(to: string, text: string): string {
return '[ALERT] ' + super.send(to, 'ACTION NEEDED: ' + text)
}
}
export class DigestNotification extends Notification {
send(to: string, text: string): string {
return super.send(to, 'TODAY\'S DIGEST — ' + text)
}
}
// --- axis 2: technology, an object literal is enough ---
export const emailChannel: Channel = {
id: 'email',
deliver: (to, body) => 'SMTP -> ' + to + ' :: ' + body, // nodemailer lives here
}
export const smsChannel: Channel = {
id: 'sms',
deliver: (to, body) => 'SMS ' + to + ' :: ' + body,
}
export const textRenderer: Renderer = { id: 'text', render: t => t }
export const htmlRenderer: Renderer = { id: 'html', render: t => '<p>' + t + '</p>' }Build the bridge in one place, at runtime
Which combination gets used is a configuration decision, not an architecture decision. It belongs in the composition root (one file, one function), read from env/config/tenant. This is where the old class-building if/else dies for good.
import type { Channel, Renderer } from './implementor'
import { emailChannel, smsChannel, htmlRenderer, textRenderer } from './refined-and-implementors'
import { AlertNotification, DigestNotification } from './refined-and-implementors'
const channels: Record<string, Channel> = { email: emailChannel, sms: smsChannel }
const renderers: Record<string, Renderer> = { text: textRenderer, html: htmlRenderer }
export function createNotification(kind: string, cfg: { channel: string, format: string }) {
const channel = channels[cfg.channel]
const renderer = renderers[cfg.format]
if (!channel || !renderer) throw new Error('unsupported config: ' + cfg.channel + '/' + cfg.format)
const Cls = kind === 'digest' ? DigestNotification : AlertNotification
return new Cls(channel, renderer)
}
const n = createNotification('alert', { channel: 'sms', format: 'html' })
console.log(n.send('0912345678', 'order A01 has shipped'))[ALERT] SMS 0912345678 :: <p>ACTION NEEDED: order A01 has shipped</p>
The minimal version — and when Bridge is an overdose
If the abstraction axis does not branch, don't keep the abstract class: a function that takes a dependency is already a Bridge, and a more honest one. You're left with one interface plus the implementor objects.
On the other hand, stop yourself with one question: does the other axis have at least two real implementors (not two mocks to decorate a diagram)? A single implementor + no plan for a second = you're paying the indirection tax and getting nothing for it. Start with a plain class and refactor when the second cell shows up.
type Channel = { id: string, deliver: (to: string, body: string) => string }
/** No abstract class, no interface file: this is still Bridge. */
export const notify = (to: string, text: string, channel: Channel) =>
channel.deliver(to, text)
notify('0912345678', 'Order A01 has shipped', { id: 'sms', deliver: (t, b) => 'SMS ' + t + ' :: ' + b })
notify('a@b.co', 'Order A01 has shipped', { id: 'email', deliver: (t, b) => 'SMTP -> ' + t + ' :: ' + b })04 — Who talks to whom
Structure
- AbstractionWhat the client calls: holds an Implementor reference and runs the shared flow (`send()`). Contains no vendor names.
- RefinedAbstractionThe branching business axis: `AlertNotification`, `DigestNotification`. Extends Abstraction, still blind to the implementor.
- ImplementorThe second axis's interface, defined by the Abstraction: `Channel.deliver(to, body)`.
- ConcreteImplementorOne concrete way of doing it: email, sms, zalo. Usually an object literal, one file per vendor, the only place that imports the SDK.
- Client / composition rootPicks the combination (channel + format + kind) in one place, read from config; builds the bridge at runtime.
Client / composition root
│ new AlertNotification(channels.sms, renderers.html)
▼
┌──────────────────────────────────────────────┐
│ Abstraction: Notification │
│ #channel: Channel #renderer: Renderer │
│ send(to, text) ─► render ─► deliver │
└──────────────────┬───────────────────────────┘
│ dependency (not extends)
┌────────────┴─────────────┐
▼ ▼
AlertNotification DigestNotification ← axis 1: business
(add freely, 0 new cells)
uses the Channel / Renderer contract
┌──────────────┬───────────┴──────┐
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌──────────┐ ← axis 2: technology
│ email │ │ sms │ │ zalo │ (add freely, 0 edits)
└─────────┘ └─────────┘ └──────────┘
nodemailer HTTP API SDK OA05 — Edit freely, run it right here
Try it: Device × Driver — add a new driver, 0 new device classes
// Axis 1: abstraction (device) — changes when a device type is added
// Axis 2: implementation (driver) — changes when a manufacturer is added
interface Driver {
readonly brand: string
powerOn(): string
volumeUp(step: number): string
}
const sony: Driver = {
brand: 'Sony',
powerOn: () => 'Sony: panel on',
volumeUp: n => 'Sony: level +' + n,
}
const lg: Driver = {
brand: 'LG',
powerOn: () => 'LG: wake from standby',
volumeUp: n => 'LG: vol +' + n,
}
class Device {
constructor(protected driver: Driver) {}
powerOn(): string { return this.driver.powerOn() }
volumeUp(step: number): string { return this.driver.volumeUp(step) }
}
class Tv extends Device {
watch(): string { return 'TV[' + this.driver.brand + '] ' + this.powerOn() }
}
class Radio extends Device {
play(step: number): string { return 'RADIO[' + this.driver.brand + '] ' + this.volumeUp(step) }
}
// 2 devices × 2 drivers: inheritance needs 4 classes, bridge needs only 2 + 2
console.log(new Tv(sony).watch())
console.log(new Tv(lg).watch())
console.log(new Radio(sony).play(5))
console.log(new Radio(lg).play(3))
// Add a new driver: 1 object, 0 new device classes
const philips: Driver = { brand: 'Philips', powerOn: () => 'Philips: on', volumeUp: n => 'Philips: +' + n }
console.log(new Tv(philips).watch())TV[Sony] Sony: panel on TV[LG] LG: wake from standby RADIO[Sony] Sony: level +5 RADIO[LG] LG: vol +3 TV[Philips] Philips: on
The same code runs on Bun: bun run demo.ts. Its output is checked automatically when the site is built.
06 — Honest about the cost
When to use it, when not to
Use it when
- You can count ≥ 2 values on both axes, and adding a value on one axis has nothing to do with the other.
- The implementation has to be chosen at build/deploy/run time (env, tenant, feature flag), not when writing code — inheritance locks that decision in at compile time.
- The code has to live with several vendors/backends/formats side by side: payment (Stripe, Portal), mail, push, storage, DB dialect, export format.
- You want to test the business axis without standing up a vendor, or test a driver without building the whole business tree.
- The vendor SDK is bulky and you want one file allowed to import it, while the rest of the codebase only sees the interface.
- You're about to write
class XxxYyyZzz— stop and count the cells in the matrix first.
Don't use it when
- Over-engineering. One implementor, and no second one coming in the next 12 months? Then Bridge is three empty files and an extra go-to-definition hop. Use a plain class and refactor when the second cell shows up.
- Wrong dependency direction: if your interface describes the vendor's API (
createTransport,sendRaw), you just wrote an Adapter, not a Bridge — the abstraction is still leaking SMTP knowledge. The interface must describe what the abstraction needs. - Hollow abstraction: every abstraction method just calls the one driver method with the same name. That's a "pass-through bridge" that adds nothing — the driver could be used directly. The abstraction must hold the shared flow (ordering, validation, retry, formatting).
- Two free-moving sides make code more expensive to read: a vendor error bubbles up to the abstraction through 3 layers. Normalize errors inside the implementor (
throw new ChannelError(...)) and log withchannel.id, or debugging at 2 a.m. will be a long night. - Three axes doesn't mean three interfaces crammed into one constructor.
Notification(channel, renderer, scheduler, template)is a sign the class has taken on too many roles again — split it, one tree per pair of axes.
07 — You have met it already, just not by name
In real code
TypeORM / Kysely / Prisma: Driver-Dialect
TypeORM declares a Driver interface that PostgresDriver, MysqlDriver, SqliteDriver, MssqlDriver all implement; DataSource (the abstraction) runs the query builder and calls the driver. Prisma goes as far as splitting driver adapters into separate packages (@prisma/adapter-pg, @prisma/adapter-libsql) so the same query engine runs on many backends. This is Bridge in the literal sense: abstraction and vendor grow independently.
Vue: createRenderer and nodeOps
@vue/runtime-core contains all the component, reactivity and patch logic — but knows nothing about the DOM. The platform supplies nodeOps (createElement, insert, patchProp...) via createRenderer(options). One abstraction, three implementations running in the wild: @vue/runtime-dom (browser), @vue/server-renderer (HTML strings for SSR/Nuxt), and custom renderers for Weex/native.
unstorage: defineDriver behind useStorage() in Nuxt
You call useStorage().setItem(key, v) the same way every time, while the driver behind it is fs, redis, cloudflare-kv-binding, http... decided by config. The storage API is the Abstraction; each driver is a ConcreteImplementor matching an interface defined by unstorage (not by Redis).
Vite/Rollup: resolver + plugin container
Rollup defines a set of hooks (resolveId, load, transform) as the contract; Vite implements them for the dev server, esbuild and SSR. Same build pipeline, while "where modules come from" changes independently of "how they get built" — two axes, one contract.
08 — Try it yourself
Exercise
You have 4 classes: `ExportCsvPg`, `ExportCsvMysql`, `ExportJsonPg`, `ExportJsonMysql`, each opening its own connection and doing its own formatting. Move them to Bridge so that adding an `xlsx` format and a `sqlite` backend costs exactly **2 new files**, with no edits to old files. Say clearly which is the Abstraction and which is the Implementor.
Hints, open them one at a time:
- Which axis changes because of product (file format), and which because of infrastructure (DB)? Draw the 2x2 matrix first.
- What should the Implementor return so the two sides stay decoupled? Hint:
query(sql): Row[], and the abstraction knows nothing about cursors/connections. - Don't forget where the bridge gets built: one
Record<string, X>registry per axis, and a single function that builds the final object.
The Abstraction is Exporter holding rows: QueryRunner; the Implementor is QueryRunner { run(sql): Row[] } (pg, mysql, sqlite), and the renderer is Serializer { name, extension, serialize(rows): string } (csv, json, xlsx). exportReport(sql, { db, format }) looks up both registries and does new Exporter(runner, serializer). Adding xlsx = 1 object + 1 registry line; adding sqlite = 1 object + 1 registry line.
type Row = Record<string, string | number>
interface QueryRunner { readonly db: string, run(sql: string): Row[] }
interface Serializer { readonly format: string, serialize(rows: Row[]): string }
class Exporter {
constructor(private runner: QueryRunner, private serializer: Serializer) {}
export(sql: string): string {
const rows = this.runner.run(sql)
return this.serializer.format + ' · ' + rows.length + ' rows · ' + this.serializer.serialize(rows)
}
}
const pg: QueryRunner = { db: 'pg', run: () => [{ id: 1 }, { id: 2 }] }
const mysql: QueryRunner = { db: 'mysql', run: () => [{ id: 7 }] }
const csv: Serializer = { format: 'csv', serialize: rows => rows.map(r => String(r.id)).join(',') }
const json: Serializer = { format: 'json', serialize: rows => JSON.stringify(rows) }
const xlsx: Serializer = { format: 'xlsx', serialize: rows => 'BIN(' + rows.length + ')' } // NEW file
const runners: Record<string, QueryRunner> = { pg, mysql }
const serializers: Record<string, Serializer> = { csv, json, xlsx }
const exportReport = (sql: string, db: string, format: string) =>
new Exporter(runners[db], serializers[format]).export(sql)
console.log(exportReport('SELECT id', 'mysql', 'xlsx'))09 — Read them in pairs to see the essence
Related patterns
- AdapterAdapter makes an **existing** API fit the API you need; Bridge defines the API first and lets many implementations implement it. In real code, Bridge usually sits in front and Adapter sits behind it, hiding the vendor SDK.
- Abstract FactoryAbstract Factory builds a **whole family** of cooperating objects; Bridge is where that family gets used. A factory is a clean way to pick the (channel + renderer) pair in the composition root.
- StrategyEasy to confuse: Strategy swaps **one behavior** (often a single function), Bridge separates **two class hierarchies** that can both branch. If your abstraction has no subclasses, what you wrote is really Strategy.
- FacadeFrom the outside, a Bridge abstraction looks like a Facade: one tidy API hiding many things. The difference is that Facade isn't about letting two sides evolve independently, and usually has no interchangeable implementations.