# BridgeThree 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.

{{< lesson-video youtube="Pa_HGyY9PLs" title="Bridge" >}}

## Nine classes

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.

```mermaid {alt="A grid of nine classes: EmailAlert, SmsAlert, PushAlert, EmailReminder, SmsReminder, PushReminder, EmailDigest, SmsDigest and PushDigest, one for every pair of kind and channel; adding Slack would add three more." caption="One class per pair: nine, and growing."}
flowchart TB
  subgraph R1[" "]
    direction LR
    A1["EmailAlert"] ~~~ A2["SmsAlert"] ~~~ A3["PushAlert"]
  end
  subgraph R2[" "]
    direction LR
    B1["EmailReminder"] ~~~ B2["SmsReminder"] ~~~ B3["PushReminder"]
  end
  subgraph R3[" "]
    direction LR
    C1["EmailDigest"] ~~~ C2["SmsDigest"] ~~~ C3["PushDigest"]
  end
  R1 ~~~ R2 ~~~ R3
  class A1,A2,A3,B1,B2,B3,C1,C2,C3 bad
```

## A camera and its lenses

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**.

```mermaid {alt="The camera analogy mapped onto code: the camera body is the abstraction (Notification), the lens is the implementor (Channel), and the lens mount that joins them is the bridge (the channel field)." caption="The camera, mapped onto the code."}
flowchart LR
  A["the body"] --> A2["abstraction: Notification"]
  B["the lens"] --> B2["implementor: Channel"]
  C["the lens mount"] --> C2["bridge: the channel field"]
  class A2 c6
  class B2 c1
  class C2 hl
```

## The obvious version: one class per pair

Here's the obvious version. A notification has one method, `send`. An email alert extends it, shouts
the text, and delivers it by email.

```java
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.

```java
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.

## Why it breaks

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.

## The key idea: two hierarchies, one field

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.

```mermaid {alt="Before and after. Before: nine pair classes, one per kind-and-channel combination. After: a Notification hierarchy (Alert, Reminder, Digest) holds a Channel (Email, Sms, Push); 3 + 3 = 6 classes." caption="Nine classes become three plus three."}
flowchart LR
  subgraph BEFORE["Before: 3 x 3 = 9 classes"]
    direction TB
    X["EmailAlert, SmsAlert, PushAlert<br/>EmailReminder, SmsReminder, PushReminder<br/>EmailDigest, SmsDigest, PushDigest"]
  end
  subgraph AFTER["After: 3 + 3 = 6 classes"]
    direction TB
    N["Notification"] -- "channel" --> CH["Channel"]
    K["Alert, Reminder, Digest"] --> N
    CH --> E["Email, Sms, Push"]
  end
  BEFORE ~~~ AFTER
  class X bad
  class N c6
  class CH c1
  class K,E good
```

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.**

## Building it

Start with the implementor. `Channel` is an interface with one method, `deliver`. It knows nothing
about alerts or reminders.

```java
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).

```java
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.

```java
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.

```java
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.

```mermaid {alt="Sequence: the caller sends 'Server is down' to an Alert; the Alert turns it into 'ALERT: SERVER IS DOWN' and calls deliver on the SmsChannel, which sends the text message. The Alert never learns how the message travels." caption="The alert never learns how."}
sequenceDiagram
  participant C as Caller
  participant A as Alert
  participant S as SmsChannel
  C->>A: send(text)
  Note over A: shout the text
  A->>S: deliver(shouted text)
  S-->>A: sent
```

The caller picks one of each. An alert over text message, and a reminder over email. Any pair, and
no new class.

```java
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.)

```java
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.

## Anatomy

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**.

```mermaid {alt="Class diagram of Bridge: Notification (abstraction) holds a Channel (implementor interface with deliver). Alert and Reminder extend Notification. EmailChannel, SmsChannel and PushChannel implement Channel." caption="Two hierarchies, joined by one field."}
classDiagram
  class Notification {
    -channel: Channel
    +send(user, text)
  }
  class Alert
  class Reminder
  class Channel {
    <<interface>>
    +deliver(user, message)
  }
  class EmailChannel
  class SmsChannel
  class PushChannel
  Notification <|-- Alert
  Notification <|-- Reminder
  Notification o--> Channel : holds
  Channel <|.. EmailChannel
  Channel <|.. SmsChannel
  Channel <|.. PushChannel
```

Four choices matter:

1. **Keep the implementor small and basic**, like `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.
2. **The abstraction decides what to say; the implementor decides how to send.** If a channel starts
   choosing the wording, the line has moved.
3. **Usually you pick the channel once**, when you build the notification. It's a field, so you could
   swap it later, but most designs never do.
4. **Someone has to build the pair.** Often a factory (see
   [Abstract Factory](/patterns/abstract-factory-pattern/)) or your dependency injection setup,
   so the rest of the code never names a channel.

## In the JDK: JDBC

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.

```java
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.

```mermaid {alt="Your code uses the JDK's Connection and Statement interfaces. DriverManager picks a registered driver by database address: the Postgres driver or the MySQL driver, which each supply the classes behind the interfaces." caption="Your code names the interfaces; the vendor supplies the rest."}
flowchart TB
  Y["your code"] --> I["Connection, Statement<br/>(JDK interfaces)"]
  DM["DriverManager<br/>picks a driver by address"] --> P["Postgres driver"]
  DM --> M["MySQL driver"]
  P -. implements .-> I
  M -. implements .-> I
  class Y c4
  class I muted
  class P,M c1
  class DM hl
```

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.

## The mix-up: "just an interface", Adapter and Strategy

Now a common mix-up: *Bridge is just an interface.* But one interface alone is plain
[polymorphism](/fundamentals/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](/patterns/adapter-pattern/), 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](/patterns/strategy-pattern/). 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 not to use it

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.

```mermaid {alt="Decision: do two things vary? If no, use plain subclasses. Does each grow for its own reasons? If no, wait. Does the second side have more than one implementation? If no, wait until the second arrives. If yes, use a bridge." caption="Bridge two dimensions, not one."}
flowchart TD
  Q1{"Do two things vary?"} -->|no| A1["plain subclasses"]
  Q1 -->|yes| Q2{"Each for its own reasons?"}
  Q2 -->|no| A2["one hierarchy is fine"]
  Q2 -->|yes| Q3{"Second side has 2+ implementations?"}
  Q3 -->|no| A3["wait until the second arrives"]
  Q3 -->|yes| A4["use a bridge"]
  class A4 good
  class A1,A2,A3 muted
```

## Recap

- When two things both vary, inheritance multiplies the classes.
- Split them into two hierarchies. The abstraction holds the implementor in a field. That field is
  the bridge.
- Three plus three, not three times three. Slack is one new class.
- It isn't an adapter or a strategy, and one dimension needs no bridge.

```mermaid {alt="Recap chain: spot two dimensions that vary for different reasons, split them into two hierarchies, join them with a field." caption="Two reasons to change, two hierarchies."}
flowchart LR
  A["two dimensions vary"] --> B["two hierarchies"] --> C["join with a field"]
  class A bad
  class B c6
  class C good
```

Checklist:

- Does one hierarchy grow in two independent directions (kind and channel, shape and colour)?
- Do the two directions change for different reasons, or for different teams?
- Does the abstraction hold the implementor in a field, and only call its small, basic methods?
- Is the second side going to have more than one implementation?
- Could a plain subclass, a strategy or an adapter do the job with less?

> **Two reasons to change, two hierarchies.**

Related lessons: [Adapter](/patterns/adapter-pattern/), [Strategy](/patterns/strategy-pattern/),
[Abstract Factory](/patterns/abstract-factory-pattern/), [Polymorphism](/fundamentals/polymorphism/).

## Further reading

- Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, *Design Patterns* (1994): Bridge.
- refactoring.guru: [Bridge](https://refactoring.guru/design-patterns/bridge).
- [`java.sql.Connection`](https://docs.oracle.com/en/java/javase/21/docs/api/java.sql/java/sql/Connection.html) and
  [`DriverManager`](https://docs.oracle.com/en/java/javase/21/docs/api/java.sql/java/sql/DriverManager.html) javadoc.
