November 26, 20269 minutes
Three kinds of notification and three channels make nine classes, and Slack makes twelve. Learn how Bridge turns that into three plus three, and how it differs from Adapter and Strategy.
Your app sends notifications. There are three kinds: alerts, reminders and digests. And three ways to deliver them: email, text message and push. Easy enough: one class for each pair. That’s nine classes. Then the team wants Slack, which is three more. And a new kind, say receipts, means four more. Every new idea multiplies the classes. There’s a better way, and it’s called the Bridge pattern.
Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows it section by section, with diagrams and a little extra depth.
Three kinds times three channels is nine classes. A fourth channel adds three; a fourth kind adds four. By the time both have grown, you have sixteen classes, and each new idea multiplies the count instead of adding to it.
Think of a camera. The body decides how you shoot. A compact is simple, and a pro body has dials. The lens decides what you see: wide, or zoom. Bodies and lenses are designed and sold separately. Any body takes any lens, because they meet at one agreed point: the lens mount.
Nobody sells a separate product for every pair. That would be four cameras to design, and two more every time a lens arrives. Next year you can buy a new lens and the body doesn’t change; buy a new body and every lens you own still fits.
In code, the body is the abstraction. The lens is the implementor. And the mount, the thing that joins them, is the bridge.
Here’s the obvious version. A notification has one method, send. An email alert extends it, shouts
the text, and delivers it by email.
abstract class Notification {
abstract void send(String user, String text);
}
class EmailAlert extends Notification {
void send(String user, String text) {
Smtp.send(user, "ALERT: " + text.toUpperCase());
}
}A text alert shouts the same way, and delivers by text message instead.
class SmsAlert extends Notification {
void send(String user, String text) {
SmsGateway.text(user, "ALERT: " + text.toUpperCase());
}
}(Smtp and SmsGateway are made-up helpers.) For one kind and two channels, that’s fair. Each
class is short, and does one clear thing.
But the grid keeps growing. Add Slack, and every kind needs a Slack version. Add a kind, and every channel needs a new class.
Worse, the same code gets pasted around. The alert wording lives in every alert class. The email sending lives in every email class. Change the wording, and you edit every alert class. Change the email provider, and you edit every email class. Miss one, and the channels disagree.
Two things change here, and for different reasons. The product team changes the kinds (what to say). The platform team changes the channels (how to send). One hierarchy is carrying both. And testing is awkward: to check the alert wording, you’d have to send a real email, because the wording and the sending live in one class.
So split the hierarchy in two. One for what the message is: alert, reminder, digest. One for how it travels: email, text, push. Now join them the way the camera does. The notification holds a channel in a field, and sends through it. That field is the bridge.
Notice the shape: it’s composition, not inheritance. A notification has a channel; it isn’t one. Three kinds plus three channels is six classes, not nine, and any kind works with any channel.
The Gang of Four put it this way (Design Patterns, 1994):
“Decouple an abstraction from its implementation so that the two can vary independently.”
Two reasons to change, two hierarchies.
Start with the implementor. Channel is an interface with one method, deliver. It knows nothing
about alerts or reminders.
public interface Channel {
void deliver(String user, String message);
}Each channel implements it. The email channel delivers by email. Text and push do the same job,
their own way (SmsChannel and PushChannel have the same shape).
public class EmailChannel implements Channel {
@Override
public void deliver(String user, String message) {
Smtp.send(user, message);
}
}Now the abstraction. Notification holds a channel, and takes it in the constructor. Its subclasses
decide what to say.
public abstract class Notification {
protected final Channel channel;
protected Notification(Channel channel) {
this.channel = channel;
}
public abstract void send(String user, String text);
}An alert shouts its text, then hands it to the channel. It never knows which channel it has.
public class Alert extends Notification {
public Alert(Channel channel) {
super(channel);
}
@Override
public void send(String user, String text) {
channel.deliver(user, "ALERT: " + text.toUpperCase());
}
}Follow one message through. The caller sends an alert to Maya. The alert shouts the text, passes it to the text message channel, and the channel delivers it. The alert never learns how.
The caller picks one of each. An alert over text message, and a reminder over email. Any pair, and no new class.
Notification a = new Alert(new SmsChannel());
Notification r = new Reminder(new EmailChannel());And Slack? One new class, the Slack channel. Every kind can use it straight away. (Naive: three new classes. Bridge: one.)
public class SlackChannel implements Channel {
@Override
public void deliver(String user, String message) {
Slack.post(user, message);
}
}Tests get easier too. A fake channel that records its messages can stand in for the real one, and no email goes out.
The pattern has four roles. Notification is the abstraction, and Alert and Reminder are
its refined abstractions. Channel is the implementor, and email, text and push are the
concrete implementors.
Four choices matter:
deliver. Don’t copy the abstraction’s methods
(sendAlert) into it. refactoring.guru’s description of the pattern says the abstraction “isn’t
supposed to do any real work on its own” and relies on the implementation for the low-level work.The JDK has a well known example, in its database API. Your code uses Connection and Statement.
Each database vendor supplies the classes behind them.
try (Connection con = DriverManager.getConnection(url);
Statement st = con.createStatement()) {
st.execute("select 1");
}Connection is an interface in java.sql, and DriverManager attempts to select an appropriate
driver from the registered JDBC drivers for the database address you give it (both from the javadoc).
Change the address, and the driver changes. Your code stays as it is.
That API is often described as a bridge, with the driver interfaces in the implementor role. Write-ups don’t agree on which piece is which, so that’s our reading.
Now a common mix-up: Bridge is just an interface. But one interface alone is plain polymorphism. The point is two hierarchies, each free to grow. And “abstraction” here doesn’t mean the Java keyword. It means the high-level layer, which asks for work and never does the low-level work itself.
Bridge looks like Adapter, because both put an object between two sides. But an adapter fixes a mismatch after the fact. A bridge is designed up front, so both sides can vary.
It also looks like Strategy. Both hold an interface in a field. But a strategy swaps one algorithm. A bridge splits a whole hierarchy in two, and is usually fixed when you construct the object. (Because you can replace the object in the field, people mix the two up; the intent and the problem are what tell them apart.)
| Pattern | Holds an interface in a field? | Purpose | Usually decided |
|---|---|---|---|
| Adapter | wraps one class | repair a mismatch that already exists | after the fact |
| Strategy | yes | swap one algorithm | at run time, as needed |
| Bridge | yes | split a hierarchy that varies two ways | up front, at construction |
Same shape, different purpose. Adapter repairs. Strategy swaps. Bridge splits.
When should you skip it? If only one thing varies, you don’t need two hierarchies. Plain subclasses are fine. If the second side will only ever have one implementation, the channel interface is indirection for nothing. Add it when the second one arrives.
A bridge costs an extra interface, and an extra hop on every call. Pay that when you can see two sides growing for their own reasons. Not before. refactoring.guru lists the same cost: it can add unnecessary complexity to a class that is already highly cohesive. And keep it light: the abstraction should do little itself, and the implementor interface should stay small. Otherwise the bridge becomes a new place for tangles.
Checklist:
Two reasons to change, two hierarchies.
Related lessons: Adapter, Strategy, Abstract Factory, Polymorphism.
java.sql.Connection and
DriverManager javadoc.