Bridge
Split an abstraction from its implementation so the two can vary independently.
Use it when
You'd otherwise end up with a class explosion from combining two dimensions of variation.
/**
* Bridge: separate what a notification says from how it is sent.
*
* Real-world scenario: an app sends alerts and reminders by email or SMS.
* Without a bridge you'd need a class per combination (EmailAlert, SmsAlert,
* EmailReminder, SmsReminder...), and every new channel doubles the count. Here
* a notification holds a reference to a sender, so the two sides vary
* independently: 2 notification types + 2 senders cover all 4 combinations.
*/
// Implementation side: how a message is delivered.
interface MessageSender {
send(to: string, text: string): void;
}
class EmailSender implements MessageSender {
send(to: string, text: string): void {
console.log(`Email to ${to}@example.com: ${text}`);
}
}
class SmsSender implements MessageSender {
send(to: string, text: string): void {
console.log(`SMS to ${to}'s phone: ${text}`);
}
}
// Abstraction side: what the notification is. It holds a sender (the bridge).
abstract class UserNotification {
protected readonly sender: MessageSender;
constructor(sender: MessageSender) {
this.sender = sender;
}
abstract notify(to: string, message: string): void;
}
class Alert extends UserNotification {
notify(to: string, message: string): void {
this.sender.send(to, `URGENT! ${message}`);
}
}
class Reminder extends UserNotification {
notify(to: string, message: string): void {
this.sender.send(to, `Reminder: ${message}`);
}
}
function clientCode(): void {
// Pick any notification type and pair it with any sender.
new Alert(new EmailSender()).notify("asha", "Payment failed");
new Alert(new SmsSender()).notify("asha", "Payment failed");
new Reminder(new EmailSender()).notify("ravi", "Invoice due tomorrow");
new Reminder(new SmsSender()).notify("ravi", "Invoice due tomorrow");
}
clientCode();
// Output:
// Email to asha@example.com: URGENT! Payment failed
// SMS to asha's phone: URGENT! Payment failed
// Email to ravi@example.com: Reminder: Invoice due tomorrow
// SMS to ravi's phone: Reminder: Invoice due tomorrowHow it works
| Role | Classes | What it does |
|---|---|---|
| Abstraction | UserNotification | Abstract class holding a MessageSender: the bridge between the two sides |
| Refined abstractions | Alert, Reminder | Decide what the message says |
| Implementation | MessageSender | Interface for how a message is delivered |
| Concrete implementations | EmailSender, SmsSender | One class per delivery channel |
| Client | clientCode() | Pairs any notification with any sender |