Bridge is for code that varies along two independent dimensions at once, such as kinds of remote control and kinds of device, or kinds of shape and ways of drawing them. Instead of one subclass per combination, it splits the design into two class hierarchies: an abstraction that offers high-level operations, and an implementation that offers low-level primitives. The abstraction holds a reference to an implementation object, and that one field is the bridge. Each side can then grow on its own, and a new class on either side works with everything on the other.
Think of it like
A universal remote and the devices it drives
A universal remote does not contain a TV. Its buttons (power, volume up, mute) are written once, in terms of a small set of signals every supported device understands: "are you on?", "set power", "what is your volume?", "set volume". Each device answers those signals its own way. Buy a new speaker and every remote you own can drive it; buy a fancier remote and it drives every device you own. The remote is the abstraction, the signal set is the implementor interface, and each device is a concrete implementor.
The problem
A home-automation app has remote controls for a TV and a radio. There is a basic remote, and a pro remote that adds a mute button. The first design that comes to mind is inheritance along both dimensions: a base Remote, one subclass per device, and a pro subclass under each of those. This is the Before version in the visualizer above.
abstract class Remote {
protected on = false;
constructor(protected volume: number) {}
togglePower() {
this.on = !this.on;
}
abstract volumeUp(): void;
}
class TvRemote extends Remote {
volumeUp() {
this.volume = Math.min(this.volume + 10, 100);
}
}
class RadioRemote extends Remote {
volumeUp() {
this.volume = Math.min(this.volume + 10, 30);
}
}
class ProTvRemote extends TvRemote {
mute() {
this.volume = 0;
}
}
class ProRadioRemote extends RadioRemote {
mute() {
this.volume = 0; // copy of ProTvRemote.mute
}
}Four classes for two kinds of remote and two devices. That is the class explosion from Composition vs Inheritance, but with a specific shape: the explosion comes from two dimensions that vary independently, and every class sits at one crossing of them.
- The count multiplies. With
Rkinds of remote andDdevices you needR × Dclasses. A speaker adds two classes; a third kind of remote then adds three more. - Two concerns are fused in one line.
Math.min(this.volume + 10, 100)mixes a remote decision (step by 10) with a device fact (a TV goes up to 100). Changing the step means editing every device's class. - Code is copied along one axis. A pro remote for each device repeats
mute(), because a class can extend only one parent:ProRadioRemotecan inherit the radio code or the pro-remote code, not both. - The two sides cannot be owned separately. A team adding devices and a team designing remotes edit the same classes, and neither can ship without the other.
The pattern
Intent: decouple an abstraction from its implementation so that the two can vary independently (Gang of Four). In practice: split one hierarchy that covers two dimensions into two hierarchies, and connect them with a field.
- Abstraction (
Remote) - The high-level side that clients use. It holds a reference to an implementor (
protected device: Device) and writes its operations,togglePower()andvolumeUp(), only in terms of the implementor's primitives. - Refined abstraction (
ProRemote) - A subclass of the abstraction that adds or changes high-level behavior, here
mute(). It reuses the inheriteddevicefield and works with every implementor. - Implementor (
Device) - The interface of the low-level side: a small set of primitives (
isOn,setPower,getVolume,setVolume). It does not have to look like the abstraction's interface, and usually should not. - Concrete implementor (
Tv,Radio) - One class per platform, vendor or device. Each implements the primitives its own way; here each enforces its own maximum volume.
- Client
- Picks one class from each side and joins them:
new ProRemote(new Radio(25)). It can also be a factory or a DI container.
The bridge itself is just the association from Remote to Device. The classes on one side of it (Remote, ProRemote) know only Device; the classes on the other side (Tv, Radio) know nothing about remotes. That is also the dependency inversion principle from SOLID Principles at work: the high-level side depends on an interface, and the low-level classes implement it.
What the visualizer shows
- Class diagram: the abstraction hierarchy on the left (
RemoteaboveProRemote), the implementor hierarchy on the right (DeviceaboveTvandRadio), and one association labeled bridge between them. Every call from a remote to a device lights that association, the violetDeviceinterface and the device class that runs. - Objects at runtime:
remoteholdsdevice = tvandproholdsdevice = radio, each drawn as an arrow from the field to the device object. Watch the device'sonandvolumefields change while the remote objects have no state of their own besides that reference. - Sequence of calls: each client call to a remote fans out into two calls on its device,
isOnthensetPower, orgetVolumethensetVolume. That fan-out is the abstraction building a high-level operation out of primitives.
Press Play, or step with the arrow buttons; the visualizer runs the classes in the code panel for real, and the caption under the stage explains each step. The Before / With Bridge toggle switches to the one-class-per-combination version, where each remote object carries the device code itself, so a client call never reaches a separate device object. Add speaker applies the change request to whichever version is shown; new classes get a new class badge, and the Change request panel beside the code compares the two versions.
Walkthrough
- 1
Create an implementor
With With Bridge selected, the client runs
new Tv(30). The objecttvholds the device state:on = false,volume = 30. - 2
Join the two hierarchies
new Remote(tv)createsremotewithdevice = tv. This field is the bridge. From now onremoteknows only that it holds someDevice. - 3
A high-level operation
remote.togglePower()callsisOn()on its device (the answer isfalse) and thensetPower(true). Both calls are declared byDevice, soTv's code runs, andtv.onbecomestrue. - 4
Another operation, the same primitives
remote.volumeUp()callsgetVolume()(30) and thensetVolume(40). The step of 10 is remote logic and lives inRemote; storing the value is device logic and lives inTv. - 5
Cross to another combination
The client creates
radiowith volume 25 and pairs it with the refined abstraction:new ProRemote(radio). No class exists for "pro remote + radio"; the combination is two objects. - 6
Inherited code, new device
pro.volumeUp()runs the codeProRemoteinherits fromRemote. It asks forsetVolume(35), and the radio stores30, its own maximum. The remote did not need to know that limit. - 7
Refined behavior
pro.mute()is the one method onlyProRemotehas. It is still written againstDevice: onesetVolume(0)call, andradio.volumebecomes0. - 8
Add a speaker (change request)
With Add speaker applied, the client builds the pro remote for
new Speaker(45)instead.volumeUp()asks for 55 and the speaker stores 50;mute()sets 0. The only new class isSpeaker, and both kinds of remote work with it.
Before and after
One class per combination
R × Dclasses: every remote kind times every device- Remote logic and device details fused in each class
mute()and the volume step copied once per device- A new device means one new class per kind of remote
- Fewer objects at runtime: one object is remote and device
With Bridge
R + Dclasses, plus theDeviceinterface- Remotes know only
Device; devices know nothing of remotes - Each piece of logic is written once, on its own side
- A new device or a new remote is one class
- Any remote can be paired with any device, even at runtime
| Change request: add a speaker | Before | With Bridge |
|---|---|---|
| Existing classes edited | 0 | 0 |
| New classes | 2 (SpeakerRemote, ProSpeakerRemote) | 1 (Speaker) |
| Lines changed in existing classes | 0 | 0 |
Neither version edits an existing class, so the difference is not in edits. It is in how the class count grows. At this size the gap is one class; it widens with every item on either list, because the Before design multiplies and the Bridge design adds:
| Remote kinds × devices | One class per combination | With Bridge (classes + interface) |
|---|---|---|
| 2 × 2 (the visualizer) | 4 + base = 5 | 2 + 2 + 1 = 5 |
| 2 × 3 (add a speaker) | 6 + base = 7 | 2 + 3 + 1 = 6 |
| 3 × 3 (add a voice remote) | 9 + base = 10 | 3 + 3 + 1 = 7 |
| 4 × 5 | 20 + base = 21 | 4 + 5 + 1 = 10 |
Variations
Choosing and switching the implementor
Usually the client picks the implementor once, at construction, and it stays for the object's lifetime. The Gang of Four note that it can even be switched at runtime (here, a setDevice(d) method). If the choice depends on the platform or configuration, keep it out of the abstraction: let a factory or a DI container (Dependency Injection) build the right implementor, and hand it in. When implementors come in matching sets (a window, a font and a cursor for each operating system), an Abstract Factory can create the right set: the factory decides which platform, and the bridge keeps the abstractions from depending on it.
Only one implementor: pimpl and handle/body
With a single implementation, the implementor interface is not needed, but splitting the class still helps. The C++ pimpl idiom (pointer to implementation) is this degenerate Bridge: the public class holds a std::unique_ptr<Impl> and the private details live in the .cpp file, so changing them does not force every client to recompile.
// widget.h: clients see only this
#include <memory>
class Widget {
public:
Widget();
~Widget(); // defined in widget.cpp, where Impl is complete
void draw();
private:
struct Impl; // declared here, defined in widget.cpp
std::unique_ptr<Impl> impl_;
};| Variation | Use it when | Example |
|---|---|---|
| Implementor fixed at construction | The pairing does not change for the object's lifetime | The remote in the visualizer; a JDBC Connection stays tied to its driver |
| Switchable implementor | The same abstraction must move between implementations | A logging handler whose formatter is replaced with setFormatter(...) |
| Shared implementor | Many abstractions can use one implementor object | Several remotes driving the same Tv instance |
| Single implementor (pimpl) | You want to hide details and cut compile dependencies, not to vary them | C++ classes with a std::unique_ptr<Impl> member |
In real code
| Where | Abstraction side | Implementation side |
|---|---|---|
| JDBC (Java) | The java.sql API that applications use: DriverManager.getConnection(url), Connection, PreparedStatement, ResultSet | Vendor drivers (PostgreSQL, MySQL, Oracle...) that implement java.sql.Driver and those interfaces. DriverManager asks each registered driver whether it accepts the URL |
java.util.logging | Handler subclasses: ConsoleHandler, FileHandler, SocketHandler | Formatter subclasses: SimpleFormatter, XMLFormatter. Any handler takes any formatter through setFormatter |
| Log4j 2 and Logback | Appenders: where a log event goes (console, file, socket) | Layouts or encoders: how the event is turned into text, such as a pattern layout or JSON |
| GUI toolkits | Toolkit widgets and windows that application code uses | A per-platform backend that draws them with the operating system's window system. Java AWT historically gave each component a native peer created by the Toolkit |
| Operating systems | A device-independent API: files, sockets, audio streams | Device drivers, one per piece of hardware |
JDBC is the textbook example because the two sides really are developed by different people: the JDK defines the API, database vendors ship drivers, and an application switches databases by changing the URL and the driver JAR. Strictly, the JDBC abstraction side is mostly interfaces implemented by the driver, so it is a lighter form of the GoF structure, but the intent (two independently evolving sides joined at one interface) is exactly Bridge.
When to use it, and when not to
Reach for Bridge when
- Two dimensions vary independently and both are expected to grow
- Class names are combinations of two lists (
UrgentSmsNotification) - Implementations are platform, vendor or device specific and should stay out of the high-level code
- Different teams own the high-level side and the implementations
- You want to pick or switch the implementation at runtime
Skip it when
- Only one dimension varies: an interface plus implementations (often Strategy) is enough
- There is one implementation and no plan for another (unless you want pimpl's compile firewall)
- The abstraction would only forward each call one to one
- You are fitting an existing class to an interface after the fact: that is Adapter
- The combinations are few and fixed
Bridge vs similar patterns
Bridge, Adapter and Strategy all have an object that holds another object behind an interface, so their class diagrams look alike. Tell them apart by when the design is made and what varies.
| Pattern | What varies | When it is applied | Key difference |
|---|---|---|---|
| Bridge | Two dimensions: the abstraction hierarchy and the implementor hierarchy | Up front, when you see both dimensions coming | Both sides are designed to grow; the implementor interface is chosen to suit the abstraction |
| Adapter | Nothing new; an existing interface is converted | After the fact, to make an incompatible class fit | Retrofitted; the adapted class was written without knowing about you |
| Strategy | One algorithm inside a context | Whenever a task has interchangeable algorithms | Same structure (a field typed as an interface). The context is usually not a hierarchy, and the strategy is one algorithm, often swapped at runtime, rather than the whole low-level implementation |
| Abstract Factory | Families of products to create | When objects must be created as matching sets | Creational, not structural. Often used together: a factory creates and configures the right implementor for a bridge |
| Composition vs Inheritance | Any combination of parts | A general principle, not a pattern | Bridge is one specific application: composition between two hierarchies |
Implementation
The visualizer's scenario as a complete program: a Device implementor interface with Tv, Radio and Speaker, and a Remote abstraction with a ProRemote refinement. The demo pairs remotes and devices freely, including the new Speaker with both kinds of remote.
from abc import ABC, abstractmethod
class Device(ABC):
"""Implementor: low-level primitives every device offers."""
@abstractmethod
def is_on(self) -> bool: ...
@abstractmethod
def set_power(self, on: bool) -> None: ...
@abstractmethod
def get_volume(self) -> int: ...
@abstractmethod
def set_volume(self, v: int) -> None: ...
class Tv(Device):
def __init__(self, volume: int) -> None:
self._on = False
self._volume = volume
def is_on(self) -> bool:
return self._on
def set_power(self, on: bool) -> None:
self._on = on
def get_volume(self) -> int:
return self._volume
def set_volume(self, v: int) -> None:
self._volume = max(0, min(v, 100)) # a TV goes to 100
class Radio(Device):
def __init__(self, volume: int) -> None:
self._on = False
self._volume = volume
def is_on(self) -> bool:
return self._on
def set_power(self, on: bool) -> None:
self._on = on
def get_volume(self) -> int:
return self._volume
def set_volume(self, v: int) -> None:
self._volume = max(0, min(v, 30)) # a radio goes to 30
# The change request: one new implementor. Nothing else is edited.
class Speaker(Device):
def __init__(self, volume: int) -> None:
self._on = False
self._volume = volume
def is_on(self) -> bool:
return self._on
def set_power(self, on: bool) -> None:
self._on = on
def get_volume(self) -> int:
return self._volume
def set_volume(self, v: int) -> None:
self._volume = max(0, min(v, 50)) # a speaker goes to 50
class Remote:
"""Abstraction: high-level operations built from the primitives."""
def __init__(self, device: Device) -> None:
self._device = device
def toggle_power(self) -> None:
self._device.set_power(not self._device.is_on())
def volume_up(self) -> None:
self._device.set_volume(self._device.get_volume() + 10)
def volume_down(self) -> None:
self._device.set_volume(self._device.get_volume() - 10)
class ProRemote(Remote):
"""Refined abstraction: adds behavior, still only knows Device."""
def mute(self) -> None:
self._device.set_volume(0)
if __name__ == "__main__":
tv = Tv(30)
remote = Remote(tv)
remote.toggle_power()
remote.volume_up()
print(tv.is_on(), tv.get_volume()) # True 40
radio = Radio(25)
pro = ProRemote(radio)
pro.volume_up()
print(radio.get_volume()) # 30 (the radio's maximum)
pro.mute()
print(radio.get_volume()) # 0
# The new Speaker works with both kinds of remote.
speaker = Speaker(45)
Remote(speaker).volume_up()
print(speaker.get_volume()) # 50
ProRemote(speaker).mute()
print(speaker.get_volume()) # 0Key takeaways
- Bridge splits a design that varies along two independent dimensions into two hierarchies, an abstraction and an implementor, joined by one field.
- The abstraction offers high-level operations and builds them from the implementor's low-level primitives;
volumeUp()isgetVolume()thensetVolume(). - Class count goes from
R × DtoR + D. In the visualizer's "Add speaker" request, Bridge adds 1 class (Speaker) where one class per combination adds 2. - Bridge is designed up front; Adapter is retrofitted. Strategy has the same shape but varies one algorithm of a single context.
- Real examples: JDBC's API and vendor drivers, logging handlers or appenders and their formatters or layouts, GUI toolkits and their platform backends.
- With only one dimension of variation, Bridge is overkill: an interface and its implementations already do the job.
Common pitfalls
- Applying Bridge when only one dimension varies. Two hierarchies where one would do add indirection and files without any benefit.
- Mirroring the abstraction's interface in the implementor, so every abstraction method forwards one to one. Keep the implementor to a small set of primitives and build the high-level operations on top.
- Leaking the implementation back up: an abstraction that checks
device instanceof Tvor casts to reach a device-only method has re-fused the two dimensions. - Choosing the implementor inside the abstraction (
this.device = os === "mac" ? new MacWindow() : ...). Let the client, a factory or a DI container pass it in. - In languages without garbage collection, forgetting who owns the implementor. Decide whether the abstraction owns it (
std::unique_ptr), shares it (std::shared_ptr) or only refers to it (a reference that must not outlive the device).
Interview tips
- When an LLD prompt has two lists that combine (notification types × channels, shapes × renderers, reports × export formats), say so explicitly and propose Bridge before the interviewer points out the class explosion.
- Draw the two hierarchies side by side with one association labeled as the bridge, then show that adding one item to either list is one class.
- Be ready to separate it from Adapter (up front vs after the fact) and from Strategy (two hierarchies vs one algorithm), and name JDBC as a real-world example.
Real-world applications
- Database access APIs (JDBC, ODBC) on top of vendor-specific drivers.
- Logging: handlers or appenders (console, file, network) combined with formatters or layouts (plain text, JSON, XML).
- Cross-platform GUI toolkits: one widget API, a backend per operating system or graphics system.
- Graphics: shapes or charts drawn by interchangeable renderers (SVG, canvas, PDF).
- Notifications: message kinds (alert, digest, reminder) sent through any channel (email, SMS, push).
- Device control: one remote or automation API driving many vendors' hardware through drivers.
Test yourself
Which situation is the clearest sign that Bridge is needed?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.