Cheatsheet
Bridge
Intent
Split an idea into two parts that can change separately (what gets done and how it's done), and join them with a reference instead of inheritance.
Structure (UML)
classDiagram
direction LR
class Reminder {
<<Abstraction>>
+send(Member member) Delivery
#title() String
#body(Member member) String
}
class ClassReminder {
<<RefinedAbstraction>>
}
class PaymentReminder {
<<RefinedAbstraction>>
}
class Channel {
<<Implementor>>
+deliver(to, title, body) Delivery
}
class EmailChannel {
<<ConcreteImplementor>>
}
class SmsChannel {
<<ConcreteImplementor>>
}
class PushChannel {
<<ConcreteImplementor>>
}
Reminder <|-- ClassReminder
Reminder <|-- PaymentReminder
Reminder o-- Channel : channel
Channel <|.. EmailChannel
Channel <|.. SmsChannel
Channel <|.. PushChannelParticipants
- Abstraction (Reminder), what the rest of the app uses; it holds a reference to the channel
- RefinedAbstraction (ClassReminder, PaymentReminder), each kind of reminder
- Implementor (Channel), the interface for how a message is delivered
- ConcreteImplementor (EmailChannel, SmsChannel, PushChannel), each channel with its rules
Reminder.java
/** The abstraction: what a reminder says. How it travels is the channel's business. */
public abstract class Reminder {
private final Channel channel; // the bridge to the implementation
protected Reminder(Channel channel) {
if (channel == null) throw new InvalidReminderException("a reminder needs a channel");
this.channel = channel;
}
public final Delivery send(Member member) {
return channel.deliver(member, title(), body(member));
}
protected abstract String title();
protected abstract String body(Member member);
}Pros
- Reminders and channels grow separately; any combination works
- Each rule lives in one place (the SMS cut, in the channel)
- The channel can be picked at runtime, by the member's preference for example
Cons
- Two hierarchies and a reference between them, more to read than one direct class
- You have to decide well what goes on each side; with a bad boundary, things cross over
- If only one dimension varies, it's extra structure
- If each channel needs different wording for each reminder, the sides aren't independent and the bridge breaks