Skip to content

Design Patterns

Bridge

Calling through the bridge adds O(1) extra work (a constant amount) — one call forwarded to whichever engine is plugged in.

The idea, in plain English

A bridge works like a universal remote control. The remote has the same buttons — power, volume, channel — no matter which TV brand you point it at: Sony, Samsung, whatever. The remote (what you use) and the TV (how it actually works inside) are built separately and connected by a bridge. Either side can change without breaking the other.

How it works

  1. 1You split a feature into two separate pieces: the 'front' that people use, and the 'engine' that does the real work.
  2. 2You have the front hold a reference to whichever engine it's connected to.
  3. 3When the front is asked to do something, it calls the engine's version. Swap the engine, and the same front now works differently underneath.

When you'd use it

Use this when a feature needs to work with several different implementations underneath. Examples: a remote working with different TV brands, or an app supporting different payment providers behind the same checkout button.

Common beginner mistakes

  • Don't let the front peek at engine-specific details. That quietly glues them back together and defeats the point of separating them.
  • Don't build a new front for every engine. Let one front work with any engine that fits the same shape.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Remote: Sony TV is on
Remote: Samsung TV is on

Not sure this is the right topic? See the learning paths → or where this leads →