A food delivery app shows a live map while your order is on its way. The customer sees the restaurant, their home and a little scooter moving between them. The rider sees a different map of the same trip: only the next stop, with the camera centred on the scooter. Two screens, two sets of rules about what to show.
Under both screens sits a map library, and the app ships with two. Most phones use one library, and phones that cannot run it get the other. The two libraries draw the same things, but they take their inputs in different shapes. So the app has two things that vary at the same time: which screen, and which library.
The same problem shows up wherever two lists multiply. A notification system has kinds of message and channels to send them on. A payments module has checkout screens and payment gateways. A billing module has invoice layouts and PDF engines. The Bridge pattern splits such a class in two along the line where it varies, and joins the halves with one reference. In this article we build the delivery map twice. The first version has one class for every screen on every library. The second puts a bridge between screens and libraries. Then we look at what the bridge costs, and how it differs from Adapter and Strategy.
All the code is Java. Every snippet without a Sketch label is cut from a project that compiles: the first-version snippets from the one-class-per-pair version, the rest from the finished design. Both programs run, and the outputs shown are what they print.
The map screens we are building
An order moves through three stages: the rider is going to the restaurant, the rider has picked up the food, and the food is delivered. The app must:
- Show the customer's tracking screen. It shows the whole trip: restaurant, home and rider, the road the rider will take, and a camera wide enough for all of them. After pickup the restaurant pin goes. After delivery only the home is left.
- Show the rider's navigation screen. It shows only the next stop and the road to it, with the camera centred on the rider. After delivery it pulls back to show the area.
- Run both screens on both map libraries, TileMaps and GeoView.
- Take a third library or a third screen as one new class, such as a screen for the restaurant's staff.
- Refuse bad input clearly: a point that is not on the Earth, a road of one point, a screen with no map.
This figure is the one to draw first in an interview. It is the whole job of the screens, and it never mentions a library. A pin is a pin, and a camera that fits three points is the same idea on any map.
The two libraries agree on what a map can show and disagree on almost everything else:
| TileMaps | GeoView | |
|---|---|---|
| A point | latitude, then longitude | [longitude, latitude], the other way round |
| A pin | addPin(lat, lng, icon) | addMarker(lngLat, colour, symbol) |
| A road | addPolyline with an array of latitudes and an array of longitudes | addLine with a list of points |
| The camera | a zoom level from 1 (half the Earth) to 20 (one street) | a height above the ground in metres |
In the project, TileMapsView and GeoViewMap stand in for the two libraries. They keep a line of text for each thing on the map, so the demo can print what each screen drew.
The first version: one class per screen and library
The obvious version writes each screen once for each library. Here is the customer's screen on TileMaps:
public void show(Delivery d) { view.removeAll(); switch (d.stage()) { case TO_RESTAURANT -> { view.addPin(d.restaurant().lat(), d.restaurant().lng(), "shop"); view.addPin(d.home().lat(), d.home().lng(), "house"); view.addPin(d.rider().lat(), d.rider().lng(), "scooter"); addRoute(d.route()); fitAll(List.of(d.rider(), d.restaurant(), d.home())); } case TO_CUSTOMER -> { // Once the food is picked up, the restaurant pin goes. view.addPin(d.home().lat(), d.home().lng(), "house"); view.addPin(d.rider().lat(), d.rider().lng(), "scooter"); addRoute(d.route()); fitAll(List.of(d.rider(), d.home())); } case DELIVERED -> { view.addPin(d.home().lat(), d.home().lng(), "house"); view.moveCamera(d.home().lat(), d.home().lng(), 16); } } }This code works, and for an app with one screen and one library it is the right code. Nothing in it is hard to follow. The trouble starts with the second screen and the second library, because the app now needs four classes: each screen on each library.
What to draw is written once per library. The customer's rules about stages and pins appear in CustomerScreenOnTileMaps and again in CustomerScreenOnGeoView. The rider's rules appear twice as well.
How to draw is written once per screen. Every GeoView class flips each point to longitude first, and each customer class works out its own camera box. A slip in one of those lines breaks one screen on one library.
The copies drift apart. Someone fixed the customer's screen so that the restaurant pin goes after pickup, and fixed it only on TileMaps. The GeoView copy still draws it:
case TO_CUSTOMER -> { map.addMarker(new double[] {d.restaurant().lng(), d.restaurant().lat()}, "orange", "shop"); map.addMarker(new double[] {d.home().lng(), d.home().lat()}, "black", "house"); map.addMarker(new double[] {d.rider().lng(), d.rider().lat()}, "purple", "scooter"); addRoute(d.route()); fitAll(List.of(d.rider(), d.home())); }The first version's program shows the same moment on both libraries:
Customer's screen, TileMaps, food picked up: addPin house 12.9116,77.6474 addPin scooter 12.9352,77.6245 addPolyline 3 points from 12.9352,77.6245 to 12.9116,77.6474 #7c3aed 6px fitBounds 12.9116,77.6245 to 12.9352,77.6474 padding 48px Customer's screen, GeoView, food picked up: addMarker [77.6245, 12.9352] orange shop addMarker [77.6474, 12.9116] black house addMarker [77.6245, 12.9352] purple scooter addLine 3 points from [77.6245, 12.9352] to [77.6474, 12.9116] solid 6px #7c3aed fitBounds [77.6245, 12.9116] to [77.6474, 12.9352]
TileMaps shows two pins after pickup. GeoView shows three, and the first one is the restaurant. Neither the compiler nor the library notices, because both lines are valid code.
Every new piece multiplies. A third library means a new class for each screen. A screen for the restaurant means a new class for each library. Three screens on three libraries is nine classes, each holding one copy of one screen's rules and one copy of one library's quirks.
The grid shows the real problem. One class is trying to vary in two directions, and a class hierarchy can only split along one of them. The Template Method pattern page meets the same limit: with subclasses, each mix needs a subclass of its own.
The idea
The pattern cuts the class in two along that line:
- What to show becomes one family of classes: a
MapScreenbase class, with one subclass per screen. - How to draw it becomes another family: a
MapCanvasinterface, with one implementation per library. - Each screen holds a canvas, given to it when it is built, and draws only through
MapCanvasmethods. That one reference is the bridge between the two families. - Each family grows on its own. A new screen is one class, and it works on every library. A new library is one class, and every screen works on it.
A screen holds a canvas but does not implement MapCanvas itself. That is the difference from a Decorator, which wraps an object of its own interface.
The screen side is called the abstraction, and its subclasses are refined abstractions. The canvas side is called the implementation, and the classes behind it are concrete implementations. Those names are easy to misread: "implementation" here means the platform underneath, not a class that implements an interface. The rest of this page says screens and canvases.
Building it, step by step
Step 1: what a screen may ask of a map
The cut needs an interface on it. MapCanvas lists everything a screen may ask of any map:
/** * What a screen can ask any map library to do. Coordinates are LatLng and * distances are metres, whatever the library itself takes. */public interface MapCanvas { /** Removes everything drawn so far. */ void clear(); /** Puts a pin of this kind at this point. */ void pin(LatLng at, PinKind kind); /** Draws a road through these points, in order. Needs at least two. */ void route(List<LatLng> path); /** Moves the camera so that every one of these points is on screen. */ void fit(List<LatLng> points); /** Centres the camera on one point, showing about this many metres across. */ void follow(LatLng at, int metresAcross);}Two things are missing from it on purpose. No screen's name appears: there is no "customer screen" and no "rider screen", only pins, roads and a camera. No library's types appear either. Points are LatLng records, and distances are metres. A screen written against this interface has no need to know which library it is on.
How much should a canvas know?
One method per screen, such as drawCustomerTracking(delivery)
Each library would then draw each screen in one call, which looks tidy. But every canvas would hold every screen's rules again, so the grid of copies comes back inside the canvases. A new screen would change the interface and every canvas.
Pins, roads and a camera, and nothing about screensOur pick
The canvas offers the few things every map can do. Screens combine them into their own pictures. A new screen uses the same five methods, so no canvas changes, unless it needs a new kind of pin. The cost is that a screen sometimes needs something the interface does not have yet, which "What it costs" comes back to.
Step 2: one canvas per library
Each canvas turns those five methods into its library's calls. Here are the pin, the camera box and the zoom for TileMaps:
@Override public void pin(LatLng at, PinKind kind) { Objects.requireNonNull(at, "at"); Objects.requireNonNull(kind, "kind"); view.addPin(at.lat(), at.lng(), iconFor(kind)); } @Override public void fit(List<LatLng> points) { Bounds box = Bounds.around(points); view.fitBounds(box.south(), box.west(), box.north(), box.east(), PADDING_PX); } @Override public void follow(LatLng at, int metresAcross) { Objects.requireNonNull(at, "at"); if (metresAcross <= 0) { throw new IllegalArgumentException("metres across must be above zero, got " + metresAcross); } view.moveCamera(at.lat(), at.lng(), zoomFor(metresAcross)); } // Each zoom level shows half the width of the one before, starting from the whole Earth. private static int zoomFor(int metresAcross) { long level = Math.round(Math.log(EARTH_METRES / metresAcross) / Math.log(2)); return (int) Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, level)); }Line 35 hands TileMaps a latitude first, as it wants. Line 55 gives it the box as south, west, north and east. Lines 69 and 70 turn metres into a zoom level. Each level shows half the width of the one before, so the level is the number of halvings from the Earth's width to the width wanted, rounded and held between 1 and 20. For 500 metres that is zoom 16.
GeoView needs the same five things in its own shape:
@Override public void pin(LatLng at, PinKind kind) { Objects.requireNonNull(at, "at"); Objects.requireNonNull(kind, "kind"); map.addMarker(lngLat(at), colourFor(kind), symbolFor(kind)); } @Override public void fit(List<LatLng> points) { Bounds box = Bounds.around(points); map.fitBounds(lngLat(new LatLng(box.south(), box.west())), lngLat(new LatLng(box.north(), box.east()))); } @Override public void follow(LatLng at, int metresAcross) { Objects.requireNonNull(at, "at"); if (metresAcross <= 0) { throw new IllegalArgumentException("metres across must be above zero, got " + metresAcross); } // GeoView's camera sees an area twice as wide as its height above the ground. map.setView(lngLat(at), metresAcross / 2.0); } private static double[] lngLat(LatLng p) { return new double[] {p.lng(), p.lat()}; }Line 63 flips a point to longitude first, and every pin, road, camera position and box corner goes through it, including the two corners on line 49. The flip that every GeoView class in the first version wrote by hand now lives in this one method. Line 59 turns metres into a camera height: this library's camera sees an area twice as wide as its height, so 400 metres across is a height of 200 metres.
Both canvases need the smallest box that holds some points, so that arithmetic lives once, in a small Bounds record that both call. Each canvas then only orders the four edges the way its library wants them.
Who turns 'show these points' into a camera?
The screen works out a zoom level
The screen knows what it wants to see, so it could work out the zoom itself. But a zoom level is a TileMaps idea. GeoView has no zoom levels at all, only a height. The screen would need to know which library it is on, and the cut between the two families would be gone.
The canvas, from points to fit or metres acrossOur pick
The screen says what it wants in words every library can serve: "fit these points" or "about 400 metres across, centred here". Each canvas turns that into its own camera. The cost is that the screen cannot ask for an exact zoom level, which it should not want anyway.
Step 3: the screens
The screen side starts with a small base class that holds the canvas:
public abstract class MapScreen { protected final MapCanvas canvas; protected MapScreen(MapCanvas canvas) { this.canvas = Objects.requireNonNull(canvas, "canvas"); } /** Draws this moment of the delivery on a blank map. */ public final void show(Delivery delivery) { Objects.requireNonNull(delivery, "delivery"); canvas.clear(); draw(delivery); } protected abstract void draw(Delivery delivery);}Line 13 is the bridge itself: one field, set once in the constructor and never changed. show checks the delivery, clears the map and then calls draw, which each screen writes. The customer's screen is a list of canvas calls for each stage:
@Override protected void draw(Delivery delivery) { switch (delivery.stage()) { case TO_RESTAURANT -> { canvas.pin(delivery.restaurant(), PinKind.RESTAURANT); canvas.pin(delivery.home(), PinKind.HOME); canvas.pin(delivery.rider(), PinKind.RIDER); canvas.route(delivery.route()); canvas.fit(List.of(delivery.rider(), delivery.restaurant(), delivery.home())); } case TO_CUSTOMER -> { canvas.pin(delivery.home(), PinKind.HOME); canvas.pin(delivery.rider(), PinKind.RIDER); canvas.route(delivery.route()); canvas.fit(List.of(delivery.rider(), delivery.home())); } case DELIVERED -> { canvas.pin(delivery.home(), PinKind.HOME); canvas.follow(delivery.home(), AROUND_HOME_METRES); } } }Lines 27 to 32 are the stage the first version got wrong. There is no restaurant pin after pickup, and this time the rule is written once. It holds on every library, because no library code is here to copy it into.
The rider's screen follows the same shape with different rules. For the first two stages it draws the next stop, the rider and the road, and centres the camera on the rider at 400 metres across:
Abstract class or interface on the screen side?
An interface, and each screen keeps its own canvas field
Interfaces are lighter, and Java classes can implement several. But each screen would declare its own canvas field and repeat the order of check, clear and draw. A screen that forgot to clear would leave the last moment's pins on the map.
An abstract class that holds the canvasOur pick
The bridge lives in one place, MapScreen, and show fixes the order for every screen. A screen can only write draw. The cost is that a screen cannot extend any other class, which these screens do not need.
Step 4: choosing a library, and changing it
The app picks the library when it builds a screen. It hands the screen a canvas, and the canvas holds the library's view:
TileMapsView tileMaps = new TileMapsView(); GeoViewMap geoView = new GeoViewMap(); MapScreen customerOnTileMaps = new CustomerTrackingScreen(new TileMapsCanvas(tileMaps)); MapScreen customerOnGeoView = new CustomerTrackingScreen(new GeoViewCanvas(geoView));Sometimes the app has to change library while it runs, for example when one library fails to load its map tiles and the app falls back to the other. The demo does that for the rider's screen:
// The app switches library by building a new screen, then draws the last moment again. TileMapsView fallback = new TileMapsView(); MapScreen riderOnTileMaps = new RiderNavigationScreen(new TileMapsCanvas(fallback)); riderOnTileMaps.show(toCustomer); print("Rider's screen, moved to TileMaps", fallback.onScreen());Changing the library while the app runs
A setter on the screen, such as useCanvas(other)
One object stays on screen and only its canvas changes. But the screen's field can no longer be final, and every reader of a screen has to ask which library it is on right now. Every test has to cover a screen before and after a switch.
Build a new screen with the other canvas, and show the last moment againOur pick
With a final field, one screen draws on one library for its whole life, which is easy to read and to test. A screen is one field and no other state, so building a new one is cheap. The app has the latest Delivery, because it draws every update, so it calls show on the new screen and the map is complete straight away. The cost is one new object per switch, which happens rarely.
Step 5: refusing bad input
Every input here comes from code: the phone's location and the screens themselves. The code that builds a Delivery from the routing service's answer turns a one-point route into the next stage, or into a two-point route, before it gets here. So every refusal is an exception for a programmer, and its message says exactly what was wrong. A LatLng refuses a latitude past 90 or a longitude past 180. A Delivery refuses a road of fewer than two points, and a delivered order that still has a road left. Each canvas refuses a short road itself, before calling its library, so the message is the same on both libraries. A missing canvas, point, pin kind or delivery throws NullPointerException at once.
Screens and canvases run on the app's main thread, the one that draws the screen, and neither is thread-safe. Nothing else calls a screen while it draws. If a library throws in the middle of draw, the screen is left half drawn. We do not try to undo that. The next show starts with clear, so the half-drawn map lasts only until the next update.
The finished design
Here is one call, traced through the objects:
The whole project is below. Click any class name in the code to open that class.
package screen; import java.util.Objects; import canvas.MapCanvas;import delivery.Delivery; /** * A screen of the app that shows a delivery on a map. It decides what to draw, * and its canvas decides how a map library draws it. */public abstract class MapScreen { protected final MapCanvas canvas; protected MapScreen(MapCanvas canvas) { this.canvas = Objects.requireNonNull(canvas, "canvas"); } /** Draws this moment of the delivery on a blank map. */ public final void show(Delivery delivery) { Objects.requireNonNull(delivery, "delivery"); canvas.clear(); draw(delivery); } protected abstract void draw(Delivery delivery);}The demo in demo/Main.java follows one order from a restaurant in Koramangala to a home a few kilometres away:
Customer's screen, TileMaps, rider going to the restaurant: addPin shop 12.9352,77.6245 addPin house 12.9116,77.6474 addPin scooter 12.9410,77.6190 addPolyline 3 points from 12.9410,77.6190 to 12.9352,77.6245 #7c3aed 6px fitBounds 12.9116,77.6190 to 12.9410,77.6474 padding 48px Customer's screen, GeoView, the same moment: addMarker [77.6245, 12.9352] orange shop addMarker [77.6474, 12.9116] black house addMarker [77.6190, 12.9410] purple scooter addLine 3 points from [77.6190, 12.9410] to [77.6245, 12.9352] solid 6px #7c3aed fitBounds [77.6190, 12.9116] to [77.6474, 12.9410] Customer's screen, TileMaps, food picked up: addPin house 12.9116,77.6474 addPin scooter 12.9352,77.6245 addPolyline 3 points from 12.9352,77.6245 to 12.9116,77.6474 #7c3aed 6px fitBounds 12.9116,77.6245 to 12.9352,77.6474 padding 48px Rider's screen, GeoView, food picked up: addMarker [77.6474, 12.9116] black house addMarker [77.6245, 12.9352] purple scooter addLine 3 points from [77.6245, 12.9352] to [77.6474, 12.9116] solid 6px #7c3aed setView [77.6245, 12.9352] altitude 200 m Customer's screen, TileMaps, delivered: addPin house 12.9116,77.6474 moveCamera 12.9116,77.6474 zoom 16 Rider's screen, moved to TileMaps: addPin house 12.9116,77.6474 addPin scooter 12.9352,77.6245 addPolyline 3 points from 12.9352,77.6245 to 12.9116,77.6474 #7c3aed 6px moveCamera 12.9352,77.6245 zoom 17 Refused: latitude must be between -90 and 90, got 129.35 a route needs at least two points, got 1
Lines 2 to 6 and lines 8 to 12 are the same screen at the same moment, drawn on the two libraries. The pins come in the same order, every GeoView point has its longitude first, and both cameras get the same box. Lines 14 to 17 are the customer's screen after pickup, with no restaurant pin. Lines 19 to 22 are the rider's screen: only home and the rider are pinned, and a camera 400 metres across becomes a height of 200 metres. Line 25 shows 500 metres around home as zoom 16. Lines 27 to 30 are the rider's screen after the switch to TileMaps, where 400 metres becomes zoom 17. The last two lines are the refusals.
What it costs
The pattern makes two kinds of change cheap.
A new library is one class. A third library needs a third canvas with five methods, and every screen works on it at once. No screen changes.
A new screen is one class. A screen for the restaurant's staff shows one order: the restaurant pin, the rider coming to collect it, and a camera that fits both. It extends MapScreen and writes draw, and it works on every library at once. No canvas changes. A screen that showed many orders at once would need a new show that takes a list, which changes the base class too.
One kind of change becomes more expensive. A new kind of drawing changes the interface. Suppose the customer's screen should shade the area the restaurant delivers to. MapCanvas needs a new method for a shaded area, and every canvas must implement it, including canvases for libraries that cannot shade an area well. A default method that does nothing would spare the canvases, but then a library that cannot shade silently draws a map without the area, which is worse than a compile error. The interface between the two families is now a contract that both sides depend on, so changing it touches everything on the library side.
A new kind of pin is a small version of the same cost. PinKind is part of the interface, so a pin for a parcel locker is one new enum value and one new case in every switch on it: one in TileMapsCanvas, two in GeoViewCanvas. The compiler points at each one that misses it.
There are smaller costs. A reader has to open two files to see what appears on a screen: the screen for what, and a canvas for how. The interface can also only offer what every library can do. A feature that only one library has, such as 3D buildings, needs a separate way in, or it stays out of the shared interface.
When the pattern is too much
If the app has one map library and no plan for a second, the cut buys nothing yet. Each screen can call the library directly:
final class CustomerTrackingScreen { private final TileMapsView view; CustomerTrackingScreen(TileMapsView view) { this.view = view; } void show(Delivery delivery) { view.removeAll(); view.addPin(delivery.home().lat(), delivery.home().lng(), "house"); // ... }}When the second library arrives, the screens' calls to the library are the lines to move into a canvas. The same holds the other way: if there is only one screen, a plain class per library is enough. The bridge earns its place when both lists are longer than one, or are about to be.
Bridge, Adapter or Strategy?
All three put an interface between one class and another, so their class diagrams look alike. The difference is why the interface is there.
| Bridge | Adapter | Strategy | |
|---|---|---|---|
| Why it exists | To let two families of classes grow apart | To make an existing class fit an interface it does not implement | To let the caller pick one rule for one job |
| When to reach for it | When two lists both vary, or soon will | When an existing class has the wrong interface | When a job has several interchangeable rules |
| Does the holding side vary too? | Yes: every screen is a subclass | Not as part of the pattern | Not as part of the pattern: one Checkout holds a list of options |
| Example | Screens and map libraries | QuickSmsAdapter around QuickSmsClient, from the Adapter page | Shipping options at checkout, from the Strategy page |
The patterns also combine, as they do here. The design is a bridge, and each class on the library side is written as an adapter.
A short way to remember it: an adapter makes one class fit an interface, a strategy swaps one rule, and a bridge splits a class in two so that both halves can grow.
In an interview
The Bridge pattern sits inside many low-level design questions where two lists multiply. A notification service with kinds of message and channels to send them on has this shape. Payment screens and payment gateways, invoice layouts and PDF engines, and alerts and paging providers have the same shape.
A good order for presenting it:
- Name the two directions out loud, and draw the grid of classes the naive design would need.
- Put the interface on the cut. Say what it offers, and that it has no screen's words and no library's types.
- Write one class from each side, then the constructor that joins them.
Common mistakes:
- A class per pair. It works for two by two, and every new screen or library then multiplies the classes.
- Screen words on the interface. A
drawCustomerScreenmethod puts every screen's rules back into every canvas. - Library words on the interface. A zoom level or a
[longitude, latitude]array ties every screen to one library. - Bridge with one direction. If only the libraries vary, an interface and an adapter per library is enough.
- A setter that swaps the canvas. The field stops being final, and every reader has to ask which library a screen is on now. A new screen with the new canvas keeps one screen on one library.
Summary
- Use Bridge when one class varies in two directions at once, such as screens and map libraries.
- Split it into two families: what to show on one side, how to draw it on the other.
- Join them with one final reference, set in the constructor: each screen holds its canvas.
- Keep the interface between them free of screen names and library types: pins, roads and metres, not screens or zoom levels.
- A new screen or a new library is then one class. A new kind of drawing changes the interface and every canvas.