Bridge – two axes of change without a class explosion
Bridge separates the abstraction (what we do) from the implementation (how we do it), so both hierarchies can evolve independently. An example of notifications and delivery channels in C#, TypeScript, Java, Go and Python.
Bridge sounds like the most abstract pattern in the whole catalog, yet it solves a very down-to-earth problem: a class hierarchy that grows in two directions at once. Bridge splits it into two independent hierarchies connected by a reference – the "bridge" – instead of inheritance.
The problem: EmailUrgentAlert, SmsUrgentAlert, PushUrgentAlert…
The pierogi place sends notifications to customers. There are urgent alerts (a failed payment) and reminders (your order arrives in 30 minutes). Each can go by email or SMS. The first design was based on inheritance:
class EmailAlert extends EmailSender { /* urgent formatting + email */ }
class SmsAlert extends SmsSender { /* urgent formatting again + SMS */ }
class EmailReminder extends EmailSender { /* reminder formatting + email */ }
class SmsReminder extends SmsSender { /* reminder formatting again + SMS */ }
// next sprint: PushAlert, PushReminder… and a third kind of noticeFour classes is nothing yet. But marketing wants push notifications and a messenger, and product wants a third kind of message (a daily summary). Alert formatting is copied into every "…Alert" class, and the 160-character limit into every "Sms…" one. Every change along one dimension means editing many classes.
| Inheritance | Bridge | |
|---|---|---|
| 1 channel | 4 classes | 5 classes |
| 2 channels | 8 classes | 6 classes |
| 3 channels | 12 classes | 7 classes |
| 4 channels | 16 classes | 8 classes |
| 5 channels | 20 classes | 9 classes |
| 6 channels | 24 classes | 10 classes |
The solution: two hierarchies and a reference between them
We recognise two independent dimensions. The abstraction answers what we communicate: Notice with the Alert and Reminder subclasses – this is where the formatting and logic of each kind of message live. The implementor answers how we deliver it: a Channel interface with EmailChannel and SmsChannel implementations – this is where transport details live, such as the SMS length limit. The abstraction receives a channel in its constructor and delegates delivery to it.
| Role | In the example | Responsibility |
|---|---|---|
| Abstraction | Notice | the high-level interface for the client; holds the implementor |
| Refined abstraction | Alert, Reminder | variants of the "what" logic |
| Implementor | Channel | primitive operations the abstraction relies on |
| Concrete implementor | EmailChannel, SmsChannel | variants of the "how" – concrete platforms, protocols, libraries |
An important difference from plain dependency injection: the implementor's interface is usually lower-level than the abstraction's. A channel only knows "deliver a title and body to a recipient"; it is the abstraction that knows an alert is written in capitals and a reminder includes the time until delivery.
Implementation in five languages
In class-based languages the abstraction is an abstract class with a channel field. In Go, instead of a hierarchy there are two structs with a field of type Channel – the bridge is simply an interface-typed field, and inheritance is not needed at all.
Notice + Channel
new Alert(new SmsChannel()).Notify("Ola", "Payment for order 1042 failed");
new Reminder(new EmailChannel(), TimeSpan.FromMinutes(30)).Notify("Ola", "Your pierogi arrive soon");
// Implementor: how a message travels.
public interface IChannel
{
void Deliver(string recipient, string title, string body);
}
public sealed class EmailChannel : IChannel
{
public void Deliver(string recipient, string title, string body) =>
Console.WriteLine($"[email to {recipient}] Subject: {title} | {body}");
}
public sealed class SmsChannel : IChannel
{
// SMS has no subject line and a hard length limit.
public void Deliver(string recipient, string title, string body)
{
var text = $"{title}: {body}";
Console.WriteLine($"[sms to {recipient}] {(text.Length > 160 ? text[..157] + "..." : text)}");
}
}
// Abstraction: what the message means. It holds a channel instead of inheriting one.
public abstract class Notice(IChannel channel)
{
protected IChannel Channel { get; } = channel;
public abstract void Notify(string recipient, string text);
}
public sealed class Alert(IChannel channel) : Notice(channel)
{
public override void Notify(string recipient, string text) =>
Channel.Deliver(recipient, "URGENT", text.ToUpperInvariant());
}
public sealed class Reminder(IChannel channel, TimeSpan lead) : Notice(channel)
{
public override void Notify(string recipient, string text) =>
Channel.Deliver(recipient, $"Reminder, {lead.TotalMinutes:0} min left", text);
}// Implementor: how a message travels.
interface Channel {
deliver(recipient: string, title: string, body: string): void;
}
class EmailChannel implements Channel {
deliver(recipient: string, title: string, body: string): void {
console.log(`[email to ${recipient}] Subject: ${title} | ${body}`);
}
}
class SmsChannel implements Channel {
// SMS has no subject line and a hard length limit.
deliver(recipient: string, title: string, body: string): void {
const text = `${title}: ${body}`;
console.log(`[sms to ${recipient}] ${text.length > 160 ? text.slice(0, 157) + "..." : text}`);
}
}
// Abstraction: what the message means. It holds a channel instead of inheriting one.
abstract class Notice {
constructor(protected readonly channel: Channel) {}
abstract notify(recipient: string, text: string): void;
}
class Alert extends Notice {
notify(recipient: string, text: string): void {
this.channel.deliver(recipient, "URGENT", text.toUpperCase());
}
}
class Reminder extends Notice {
constructor(channel: Channel, private readonly leadMinutes: number) {
super(channel);
}
notify(recipient: string, text: string): void {
this.channel.deliver(recipient, `Reminder, ${this.leadMinutes} min left`, text);
}
}
new Alert(new SmsChannel()).notify("Ola", "Payment for order 1042 failed");
new Reminder(new EmailChannel(), 30).notify("Ola", "Your pierogi arrive soon");import java.time.Duration;
// Implementor: how a message travels.
interface Channel {
void deliver(String recipient, String title, String body);
}
class EmailChannel implements Channel {
public void deliver(String recipient, String title, String body) {
System.out.printf("[email to %s] Subject: %s | %s%n", recipient, title, body);
}
}
class SmsChannel implements Channel {
// SMS has no subject line and a hard length limit.
public void deliver(String recipient, String title, String body) {
String text = title + ": " + body;
System.out.printf("[sms to %s] %s%n", recipient, text.length() > 160 ? text.substring(0, 157) + "..." : text);
}
}
// Abstraction: what the message means. It holds a channel instead of inheriting one.
abstract class Notice {
protected final Channel channel;
protected Notice(Channel channel) { this.channel = channel; }
abstract void notify(String recipient, String text);
}
class Alert extends Notice {
Alert(Channel channel) { super(channel); }
void notify(String recipient, String text) { channel.deliver(recipient, "URGENT", text.toUpperCase()); }
}
class Reminder extends Notice {
private final Duration lead;
Reminder(Channel channel, Duration lead) { super(channel); this.lead = lead; }
void notify(String recipient, String text) {
channel.deliver(recipient, "Reminder, " + lead.toMinutes() + " min left", text);
}
}
public class Notifications {
public static void main(String[] args) {
new Alert(new SmsChannel()).notify("Ola", "Payment for order 1042 failed");
new Reminder(new EmailChannel(), Duration.ofMinutes(30)).notify("Ola", "Your pierogi arrive soon");
}
}package main
import (
"fmt"
"strings"
"time"
)
// Channel is the implementor: how a message travels.
type Channel interface {
Deliver(recipient, title, body string)
}
type EmailChannel struct{}
func (EmailChannel) Deliver(recipient, title, body string) {
fmt.Printf("[email to %s] Subject: %s | %s\n", recipient, title, body)
}
// SmsChannel has no subject line and a hard length limit.
type SmsChannel struct{}
func (SmsChannel) Deliver(recipient, title, body string) {
text := title + ": " + body
if len(text) > 160 {
text = text[:157] + "..."
}
fmt.Printf("[sms to %s] %s\n", recipient, text)
}
// Alert and Reminder are refined abstractions: what the message means.
// Each holds a Channel instead of being tied to one.
type Alert struct{ Channel Channel }
func (a Alert) Notify(recipient, text string) {
a.Channel.Deliver(recipient, "URGENT", strings.ToUpper(text))
}
type Reminder struct {
Channel Channel
Lead time.Duration
}
func (r Reminder) Notify(recipient, text string) {
title := fmt.Sprintf("Reminder, %.0f min left", r.Lead.Minutes())
r.Channel.Deliver(recipient, title, text)
}
func main() {
Alert{Channel: SmsChannel{}}.Notify("Ola", "Payment for order 1042 failed")
Reminder{Channel: EmailChannel{}, Lead: 30 * time.Minute}.Notify("Ola", "Your pierogi arrive soon")
}from abc import ABC, abstractmethod
from datetime import timedelta
from typing import Protocol
class Channel(Protocol):
"""Implementor: how a message travels."""
def deliver(self, recipient: str, title: str, body: str) -> None: ...
class EmailChannel:
def deliver(self, recipient: str, title: str, body: str) -> None:
print(f"[email to {recipient}] Subject: {title} | {body}")
class SmsChannel:
def deliver(self, recipient: str, title: str, body: str) -> None:
# SMS has no subject line and a hard length limit.
text = f"{title}: {body}"
print(f"[sms to {recipient}] {text if len(text) <= 160 else text[:157] + '...'}")
class Notice(ABC):
"""Abstraction: what the message means. It holds a channel instead of inheriting one."""
def __init__(self, channel: Channel) -> None:
self.channel = channel
@abstractmethod
def notify(self, recipient: str, text: str) -> None: ...
class Alert(Notice):
def notify(self, recipient: str, text: str) -> None:
self.channel.deliver(recipient, "URGENT", text.upper())
class Reminder(Notice):
def __init__(self, channel: Channel, lead: timedelta) -> None:
super().__init__(channel)
self.lead = lead
def notify(self, recipient: str, text: str) -> None:
minutes = int(self.lead.total_seconds() // 60)
self.channel.deliver(recipient, f"Reminder, {minutes} min left", text)
if __name__ == "__main__":
Alert(SmsChannel()).notify("Ola", "Payment for order 1042 failed")
Reminder(EmailChannel(), timedelta(minutes=30)).notify("Ola", "Your pierogi arrive soon")The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- Step by step
- When to use it and when not to
- Related patterns
- In practice
- Quick check
- Summary