Bridge pattern
medium 50 minThe 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
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
1994
The book Design Patterns appears on 31 October. It lists Bridge among its structural patterns, with Handle/Body as its other name.
1997
JDK 1.1 arrives on 19 February with JDBC: programs on one side, database drivers on the other.
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.
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.
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
1/3One device
Looks reasonable: a basic remote and an advanced one that extends it.
extends (is a)
Multiply or add
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")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
1/4The side clients see
Abstraction offers operations. It does not know any platform.
useshas (lives on)extends (is a)implements
operation() is what clients want. step() is what a platform can do.The same circle, two renderers
draw twice. In between only one reference has changed.What belongs on which side?
| Question | Abstraction | Implementor |
|---|---|---|
| Who decides it? | The user or the product | The platform or the vendor |
| Words | circle, remote, dialog | fill polygon, set volume, native handle |
| State | radius, muted volume, title | buffers, sockets, handles |
| Tests | With a fake implementor | Against the real platform |
| Changes when | A feature is added | A platform is added or updated |
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
WindowImplto draw a frame, a text, a button.Remotes and devices
Basic and advanced remote. TV, radio, DVD player.
muteis written once, withvolumeandset_volume.
A window on three platforms
1/3Window
open is written once: create a frame, draw the title, draw the close button.
has (lives on)extends (is a)implements
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?
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
UrgentandDigestdecide when and what, aChannelknows 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
| Pattern | Question it answers | When | Difference |
|---|---|---|---|
| Bridge | How do two sides grow apart? | Planned | Two hierarchies |
| Adapter | How do I use this class that does not fit? | Afterwards | One existing class is wrapped |
| Strategy | Which algorithm? | Any time | One side varies. The context has no subclasses |
| Abstract factory | How do I create things that belong together? | Creation | Often creates the implementor of a bridge |
| State | What does this event mean now? | At run time, by itself | The held object replaces itself |
| Template method | Which steps does a subclass fill in? | Compile time | Inheritance instead of a held object |
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
drawyou 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.