AlgoViz

Bridge pattern

medium 50 min

The Bridge pattern splits one exploding hierarchy into two that are joined by a reference, so that what is wanted and how a platform does it can grow apart.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:19

Bridge

1:03Reel

Theory

Read or listen first. About 2 min.

What it is

The Bridge pattern is a structural design pattern. It takes a class that varies in two ways and splits it into two hierarchies: the abstraction, which clients use, and the implementor, which does the platform's part.

The abstraction holds a reference to an implementor. This reference is the bridge. It is composition (has a) in place of inheritance (is a).

Another name is Handle/Body: the handle is what you hold, the body does the work.

Why it exists

Inheritance can express one question. With two questions it needs a class for each pair of answers, and code is copied between the branches.

With two hierarchies each variant is one class. Pairs are made by passing an object, also while the program runs.

It also keeps clients away from platform types. In C++ this even shortens compile times and keeps libraries binary compatible.

A short history

  1. 1994

    The book Design Patterns appears on 31 October. It lists Bridge among its structural patterns, with Handle/Body as its other name.

  2. 1997

    JDK 1.1 arrives on 19 February with JDBC: programs on one side, database drivers on the other.

  3. 2023

    Go 1.21 brings log/slog: a Logger for callers, and a Handler interface for the side that formats and writes.

Words to know

Abstraction
The side that clients use. It says what is wanted.
Refined abstraction
A variant of the abstraction.
Implementor
The interface of the platform side.
Concrete implementor
One platform.
Handle and body
Other words for abstraction and implementor.
Class explosion
One class for each pair of variants.
Primitive step
A small operation of the implementor, from which features are built.
Capability
A question such as can("blur") about an optional step.
Pimpl
Pointer to implementation: a bridge with one implementor, to hide private members in C++.
Contract test
One suite that every implementor must pass.
Lowest common part
Offering only what all platforms can do.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 3

Client calls the abstraction. It knows no platform

Understand it

Start here

Two things that change, one class hierarchy

A puppet can be a fox or a queen. It can be moved with a rod or with strings. If each combination is carved from one piece of wood, two choices become a whole shelf. The Bridge pattern takes the two choices apart and joins them with a hook.

Puppets and sticks

The ring and the hook are small. They decide whether the two shelves can grow apart.

Four parts

  • Abstraction

    What clients use: Shape, Remote, Window. Holds a reference to an implementor and is written in terms of it.

  • Refined abstraction

    Variants of the first side: Circle, AdvancedRemote, DialogWindow.

  • Implementor

    The interface of the second side: DrawingApi, Device, WindowImpl. Small steps, not finished services.

  • Concrete implementor

    Variants of the second side: OpenGlRenderer, Tv, MacImpl.

Why

The class explosion

You have remote controls, basic and advanced. You have devices: TV, radio, DVD player. With inheritance alone, a remote for a device is a class of its own: BasicTvRemote, AdvancedTvRemote, BasicRadioRemote and so on.

The design that hurts

«abstract»Remote+ power()BasicTvRemote+ power()AdvancedTvRemote+ mute()

1/3One device

Looks reasonable: a basic remote and an advanced one that extends it.

extends (is a)

The smell: class names made of two nouns, and the same method body in three branches of the tree.

Multiply or add

M×NagainstM+NM \times N \quad \text{against} \quad M + N
2 remotes and 3 devices: 6 against 5. 3 shapes and 3 renderers: 9 against 6. 5 and 6: 30 against 11. Counted are the concrete classes. Bridge also needs its two base types, so 2 and 2 is 4 against 4 plus 2: too early.
Python
def pairs(m, n):    return m * ndef bridge(m, n):    return m + n + 2            # and the two base typesfor m, n in [(2, 2), (2, 3), (3, 3), (4, 4), (5, 6)]:    print(f"{m} x {n}:  pairs {pairs(m, n):2}   bridge {bridge(m, n):2}   one more implementation costs {m} or 1")
Run it. The total is not the point, the last column is: what does the next change cost?
Edit and run it in your browser

Two hierarchies

  • A class for each variant
  • Each side tested alone
  • Any pair, chosen at run time
  • Clients see the abstraction only

One hierarchy

  • A class for each pair
  • Code copied between branches
  • The pair is fixed when you compile
  • Client code names the platform

The idea

Has a, not is a

Find the two questions that a class answers. Which shape? Which renderer? Give each question its own hierarchy. Then let one side have the other.

The Bridge pattern in general

Client+ doWork()«abstract»Abstraction# impl: Implementor+ operation()

1/4The side clients see

Abstraction offers operations. It does not know any platform.

useshas (lives on)extends (is a)implements

The two interfaces are different. operation() is what clients want. step() is what a platform can do.

The same circle, two renderers

The client calls draw twice. In between only one reference has changed.

What belongs on which side?

QuestionAbstractionImplementor
Who decides it?The user or the productThe platform or the vendor
Wordscircle, remote, dialogfill polygon, set volume, native handle
Stateradius, muted volume, titlebuffers, sockets, handles
TestsWith a fake implementorAgainst the real platform
Changes whenA feature is addedA platform is added or updated
If you can not decide for a method, look at who asks for a change of it.

Examples

Three pairs you can draw

  • Shapes and renderers

    Circle, square, triangle. OpenGL, DirectX, Vulkan. 3 plus 3 instead of 9.

  • Windows and platforms

    Window, dialog, transparent window. Windows, macOS, Linux. The window asks a WindowImpl to draw a frame, a text, a button.

  • Remotes and devices

    Basic and advanced remote. TV, radio, DVD player. mute is written once, with volume and set_volume.

A window on three platforms

bridge«abstract»Window# impl: WindowImpl+ open(title)+ close()«interface»WindowImpl+ createFrame(title)+ drawText(x, y, s)+ drawButton(label)

1/3Window

open is written once: create a frame, draw the title, draw the close button.

has (lives on)extends (is a)implements

3 kinds of window and 3 platforms: 6 classes next to the interface instead of 9.

Choosing

When to use it and when not

Use it when

  • Two things vary, and for different reasons
  • The pair should be chosen at run time
  • A change of the platform must not reach clients
  • Several objects share one implementation
  • You must hide implementation details, also from the compiler (C++)

Leave it when

  • There is one implementation and no second in sight
  • Only one side varies: that is Strategy or plain polymorphism
  • The sides are not independent: half of the pairs make no sense
  • The interface between them changes every week
  • The program is small and 2 times 2 is all there will be

Is this a bridge?

The last question is the real one. Without stable steps between the sides, a bridge is a wall with holes.

Notifications are urgent or digest, and go by SMS, mail or push. How do you build them?

BreaksUrgentSms, UrgentMail, UrgentPush, DigestSms ...
How
A class for each pair, with a common parent.
Limit
6 now, 9 with a third kind. The rule "urgent repeats after 5 minutes" stands in 3 places.
Choose when
Never, once both sides grow.
WorksOne class with two switches
How
send(kind, channel) with a switch for each.
Limit
Short, and every change edits the same method. Tests need all channels.
Choose when
For a script.
StrongNotification holds a Channel
How
Urgent and Digest decide when and what, a Channel knows how to deliver one text.
Limit
You must decide what a channel can do: length, picture, reply.
Choose when
When both lists will grow, which is usual here.

Neighbours

Bridge and the patterns that look like it

PatternQuestion it answersWhenDifference
BridgeHow do two sides grow apart?PlannedTwo hierarchies
AdapterHow do I use this class that does not fit?AfterwardsOne existing class is wrapped
StrategyWhich algorithm?Any timeOne side varies. The context has no subclasses
Abstract factoryHow do I create things that belong together?CreationOften creates the implementor of a bridge
StateWhat does this event mean now?At run time, by itselfThe held object replaces itself
Template methodWhich steps does a subclass fill in?Compile timeInheritance instead of a held object
Strategy and Bridge can look the same on paper. Bridge talks about two growing families, Strategy about one exchangeable step.

What you gain and what you pay

  • Independent

    Both sides vary, are tested and are released apart.

  • Extensible

    One new class on either side, and all pairs exist.

  • Hidden details

    Clients never see a platform type. In C++ they do not even include its header.

  • One more hop

    To read draw you open two classes.

  • A hard interface

    The steps in the middle are used by all on the left and built by all on the right. A change there touches both.

Summary

The whole topic in one minute.

Two questions, two hierarchies, one reference. Arrows cross the middle in one direction only.

The implementor has small steps named after the platform. Abstractions build features from them and keep the state of features.

In production: swap at a safe moment, resources belong to the implementor, one place chooses, new steps come with a default, and tests run on each side with a contract between them.

  • If a class answers two questions, each with growing answers, give each question its own hierarchy.
  • The bridge is one field: the abstraction has an implementor. Arrows go one way only.
  • M plus N instead of M times N. What matters is the cost of the next change.
  • The implementor offers small steps of the platform, not the operations of the abstraction.
  • It is planned. If you are fitting a finished class, it is an adapter.
  • Wait for the second variant on both sides before you build it.

Sources