These are the notes for Low-Level Design (LLD) episode 31, the fifth structural pattern (a pattern about how classes and objects are put together). Last time the Facade gave a group of classes one front door. Today's problem comes from using inheritance too eagerly: when two separate ideas are glued into one class tree, the number of classes multiplies, and a bug fix copied into one class goes missing from another. We watch Priya's bank app lose a reminder SMS that way, then invent the Bridge: two hierarchies joined by one field. Every program was actually run with javac Main.java && java -cp . Main (Java 21). Outputs are real.
1. The real-life idea: a switchboard
| At home | In code |
|---|---|
| Kinds of switch: a plain on-off switch, a timer switch | The abstraction: the high-level side the user talks to |
| Appliances: a fan, a bulb | The implementation: the low-level side that does the work |
| The wire between them: any switch can be wired to any appliance | The bridge: a field in the abstraction that holds an implementation |
| Buy an AC: no new kinds of switch needed | Vary independently: each side grows on its own |
Nobody builds a special "timer-fan switch" and a separate "timer-bulb switch". The wire lets you combine them.
2. The problem: one subclass per combination
Priya's bank app sends two kinds of message, an alert ("card used") and a reminder ("bill due"), over two channels, SMS and email. The obvious design is one subclass for every pair: AlertSms, AlertEmail, ReminderSms, ReminderEmail.
SmsGateway stands in for the real SMS company: it rejects any SMS longer than 30 characters. Last week a long alert was rejected, so someone fixed AlertSms (cut the text to 27 characters plus ...). The same SMS code had been copied into ReminderSms, and nobody fixed it there:
class SmsGateway { // the SMS company: 30 characters max
static void send(String phone, String text) {
if (text.length() > 30) System.out.println(" SMS REJECTED: " + text.length() + " chars, limit 30");
else System.out.println(" SMS to " + phone + ": " + text);
}
}
abstract class Message { abstract void send(String to, String text); }
class AlertSms extends Message {
void send(String to, String text) { String t = "ALERT: " + text.toUpperCase();
SmsGateway.send(to, t.length() > 30 ? t.substring(0, 27) + "..." : t); } // fixed last week
}
class AlertEmail extends Message {
void send(String to, String text) { System.out.println(" Email to " + to + ": ALERT: " + text); }
}
class ReminderSms extends Message {
void send(String to, String text) { SmsGateway.send(to, "Reminder: " + text); } // copy: no fix
}
class ReminderEmail extends Message {
void send(String to, String text) { System.out.println(" Email to " + to + ": Reminder: " + text); }
}
public class Main {
public static void main(String[] args) {
new AlertSms().send("98100 12345", "card used for Rs 4,999");
new ReminderSms().send("98100 12345", "electricity bill due on 10 Nov");
}
}
SMS to 98100 12345: ALERT: CARD USED FOR RS 4,999
SMS REJECTED: 40 chars, limit 30
No compiler error, no exception: Asha simply never hears that her bill is due.
(cond ? a : b is the ternary operator: if cond is true the value is a, otherwise b. substring(0, 27) takes characters 0 to 26.)
Why it failed
- Two ideas that change separately (the kind of message and the channel) were glued into one inheritance tree.
- The number of classes is kinds × channels. This is called a class explosion: every time either side grows, the number of classes multiplies.
| Kinds | Channels | One subclass per pair | With a bridge |
|---|---|---|---|
| 2 | 2 | 4 | 4 |
| 3 | 3 | 9 | 6 |
| 4 | 5 | 20 | 9 |
- The channel code is copied into every subclass for that channel, and every copy is a place where a fix can go missing.
new AlertSms()fixes the pair when the code is written (at compile time). If Asha switches to email tomorrow, we need a different class; we can't choose at runtime (while the program runs).
3. The fix: two hierarchies and a bridge
Split the design in two. The channel becomes its own interface with its own classes. The message keeps a channel in a field.
class SmsGateway { // the SMS company: 30 characters max
static void send(String phone, String text) {
if (text.length() > 30) System.out.println(" SMS REJECTED: " + text.length() + " chars, limit 30");
else System.out.println(" SMS to " + phone + ": " + text);
}
}
interface Channel { void deliver(String to, String text); } // implementor
class Sms implements Channel { public void deliver(String to, String text) { // the fix, once
SmsGateway.send(to, text.length() > 30 ? text.substring(0, 27) + "..." : text); } }
class Email implements Channel { public void deliver(String to, String text) {
System.out.println(" Email to " + to + ": " + text); } }
abstract class Message { // abstraction
protected final Channel channel; // the bridge
Message(Channel channel) { this.channel = channel; }
abstract void send(String to, String text);
}
class Alert extends Message { Alert(Channel c) { super(c); }
void send(String to, String text) { channel.deliver(to, "ALERT: " + text.toUpperCase()); } }
class Reminder extends Message { Reminder(Channel c) { super(c); }
void send(String to, String text) { channel.deliver(to, "Reminder: " + text); } }
public class Main {
public static void main(String[] args) {
Channel sms = new Sms(), email = new Email();
new Alert(sms).send("98100 12345", "card used for Rs 4,999");
new Reminder(sms).send("98100 12345", "electricity bill due on 10 Nov");
new Reminder(email).send("asha@mail.in", "electricity bill due on 10 Nov");
}
}
SMS to 98100 12345: ALERT: CARD USED FOR RS 4,999
SMS to 98100 12345: Reminder: electricity bill ...
Email to asha@mail.in: Reminder: electricity bill due on 10 Nov
Channelis an interface with one method,deliver.SmsandEmailimplement it. The 30-character fix lives once, insideSms.Messageis an abstract class (it can't be created withnewon its own; subclasses fill insend). It holds aChannelin aprotected finalfield, given through its constructor. That field is the bridge.AlertandReminderonly decide the words. They pass the text to whatever channel they were given, and don't know whether it's SMS or email.- To make a message, you combine:
new Reminder(sms),new Reminder(email).
Handing work over to another object like this is called delegation: Alert.send delegates the delivery to channel.deliver.
4. It has a name: the Bridge pattern
Intent (SourceMaking, Bridge): "Decouple an abstraction from its implementation so that the two can vary independently." Also: "Publish interface in an inheritance hierarchy, and bury implementation in its own inheritance hierarchy."
Decouple means: remove the hard link between two things, so each can change without touching the other.
| Role | Meaning | In our code |
|---|---|---|
| Abstraction | The high-level side the client talks to; holds a reference to an implementor | Message |
| Refined abstraction | A subclass of the abstraction that adds its own behaviour | Alert, Reminder, Promo |
| Implementor | The interface for the low-level work | Channel |
| Concrete implementor | A real class implementing the implementor | Sms, Email, Push |
| The bridge | The has-a link (field) from abstraction to implementor | protected final Channel channel |
A warning about two words
In this pattern, abstraction means the what side (send an alert) and implementation means the how side (deliver by SMS). These are not the same as Java's abstract keyword or the implements keyword, even though both appear in the code. They are names for the two sides.
5. Growing both sides, and choosing at runtime
A new channel (Push) costs one class. A new kind (Promo) costs one class. With one subclass per pair it would have been five more (AlertPush, ReminderPush, PromoSms, PromoEmail, PromoPush).
import java.util.Map;
interface Channel { void deliver(String to, String text); } // implementors
class Sms implements Channel { public void deliver(String to, String text) {
System.out.println(" SMS to " + to + ": " + (text.length() > 30 ? text.substring(0, 27) + "..." : text)); } }
class Email implements Channel { public void deliver(String to, String text) {
System.out.println(" Email to " + to + ": " + text); } }
class Push implements Channel { public void deliver(String to, String text) { // NEW: one class
System.out.println(" Push to " + to + "'s phone: " + text); } }
abstract class Message { // abstractions
protected final Channel channel;
Message(Channel channel) { this.channel = channel; }
abstract void send(String to, String text);
}
class Alert extends Message { Alert(Channel c) { super(c); }
void send(String to, String text) { channel.deliver(to, "ALERT: " + text.toUpperCase()); } }
class Reminder extends Message { Reminder(Channel c) { super(c); }
void send(String to, String text) { channel.deliver(to, "Reminder: " + text); } }
class Promo extends Message { Promo(Channel c) { super(c); } // NEW: one class
void send(String to, String text) { channel.deliver(to, "Offer: " + text); } }
public class Main {
public static void main(String[] args) {
Map<String, Channel> channels = Map.of("sms", new Sms(), "email", new Email(), "push", new Push());
String setting = "push"; // Asha's choice, read at runtime
new Alert(channels.get(setting)).send("asha", "card used for Rs 4,999");
new Promo(channels.get(setting)).send("asha", "20% off chai this Sunday");
new Promo(channels.get("sms")).send("98100 12345", "20% off chai this Sunday");
}
}
Push to asha's phone: ALERT: CARD USED FOR RS 4,999
Push to asha's phone: Offer: 20% off chai this Sunday
SMS to 98100 12345: Offer: 20% off chai this Su...
Map.of(...)makes a small unmodifiable map (keys can't be added or removed later). Here it maps a setting name to a channel.- The channel is picked from Asha's setting while the program runs. Change the setting and the same
Alertclass uses a different channel, with nothing recompiled.
One call, step by step
- The client calls
sendon aPromothat was given thePushchannel. - Abstraction side:
Promodecides the words:"Offer: " + text. - Across the bridge: it calls
channel.deliver(to, text)without knowing which channel it is. - Implementation side:
Pushdoes the delivery.
6. The textbook example: shapes and renderers
Shapes (Circle, Square) are the abstraction. A renderer (the code that actually draws) is the implementor: VectorRenderer describes clean lines, PixelRenderer fills in dots on a screen.
import java.util.List;
interface Renderer { void circle(int radius); void square(int side); } // implementor
class VectorRenderer implements Renderer {
public void circle(int r) { System.out.println(" vector: circle, radius " + r); }
public void square(int s) { System.out.println(" vector: square, side " + s); }
}
class PixelRenderer implements Renderer {
public void circle(int r) { System.out.println(" pixels: " + (int) (Math.PI * r * r) + " dots, circle"); }
public void square(int s) { System.out.println(" pixels: " + s * s + " dots, square"); }
}
abstract class Shape { // abstraction
protected final Renderer renderer;
Shape(Renderer renderer) { this.renderer = renderer; }
abstract void draw();
}
class Circle extends Shape { final int radius;
Circle(Renderer r, int radius) { super(r); this.radius = radius; }
void draw() { renderer.circle(radius); } }
class Square extends Shape { final int side;
Square(Renderer r, int side) { super(r); this.side = side; }
void draw() { renderer.square(side); } }
public class Main {
public static void main(String[] args) {
for (Renderer r : List.of(new VectorRenderer(), new PixelRenderer()))
{ new Circle(r, 5).draw(); new Square(r, 4).draw(); }
}
}
vector: circle, radius 5
vector: square, side 4
pixels: 78 dots, circle
pixels: 16 dots, square
Math.PI * 5 * 5 is about 78.5; (int) cuts it to 78. Two shapes and two renderers give four combinations with four small classes. Without the bridge you'd write VectorCircle, PixelCircle, VectorSquare, PixelSquare, and every new shape or renderer would multiply them.
List.of(...) makes a small unmodifiable list; the for-each loop for (Renderer r : list) visits each item in turn.
7. Mistakes the compiler catches
Forgetting super(c). Message has only one constructor, and it needs a Channel. A subclass constructor that doesn't call it:
class SmsGateway { // the SMS company: 30 characters max
static void send(String phone, String text) {
if (text.length() > 30) System.out.println(" SMS REJECTED: " + text.length() + " chars, limit 30");
else System.out.println(" SMS to " + phone + ": " + text);
}
}
interface Channel { void deliver(String to, String text); } // implementor
class Sms implements Channel { public void deliver(String to, String text) { // the fix, once
SmsGateway.send(to, text.length() > 30 ? text.substring(0, 27) + "..." : text); } }
class Email implements Channel { public void deliver(String to, String text) {
System.out.println(" Email to " + to + ": " + text); } }
abstract class Message { // abstraction
protected final Channel channel; // the bridge
Message(Channel channel) { this.channel = channel; }
abstract void send(String to, String text);
}
class Alert extends Message { Alert(Channel c) { }
void send(String to, String text) { channel.deliver(to, "ALERT: " + text.toUpperCase()); } }
class Reminder extends Message { Reminder(Channel c) { super(c); }
void send(String to, String text) { channel.deliver(to, "Reminder: " + text); } }
public class Main {
public static void main(String[] args) {
Channel sms = new Sms(), email = new Email();
new Alert(sms).send("98100 12345", "card used for Rs 4,999");
new Reminder(sms).send("98100 12345", "electricity bill due on 10 Nov");
new Reminder(email).send("asha@mail.in", "electricity bill due on 10 Nov");
}
}
Main.java:17: error: constructor Message in class Message cannot be applied to given types;
class Alert extends Message { Alert(Channel c) { }
^
required: Channel
found: no arguments
reason: actual and formal argument lists differ in length
1 error
Every subclass must pass the channel up with super(c). That's a good thing: a message without a channel can't even be built.
Making the bridge field private. private means only Message itself can use it, not its subclasses:
class SmsGateway { // the SMS company: 30 characters max
static void send(String phone, String text) {
if (text.length() > 30) System.out.println(" SMS REJECTED: " + text.length() + " chars, limit 30");
else System.out.println(" SMS to " + phone + ": " + text);
}
}
interface Channel { void deliver(String to, String text); } // implementor
class Sms implements Channel { public void deliver(String to, String text) { // the fix, once
SmsGateway.send(to, text.length() > 30 ? text.substring(0, 27) + "..." : text); } }
class Email implements Channel { public void deliver(String to, String text) {
System.out.println(" Email to " + to + ": " + text); } }
abstract class Message { // abstraction
private final Channel channel; // the bridge
Message(Channel channel) { this.channel = channel; }
abstract void send(String to, String text);
}
class Alert extends Message { Alert(Channel c) { super(c); }
void send(String to, String text) { channel.deliver(to, "ALERT: " + text.toUpperCase()); } }
class Reminder extends Message { Reminder(Channel c) { super(c); }
void send(String to, String text) { channel.deliver(to, "Reminder: " + text); } }
public class Main {
public static void main(String[] args) {
Channel sms = new Sms(), email = new Email();
new Alert(sms).send("98100 12345", "card used for Rs 4,999");
new Reminder(sms).send("98100 12345", "electricity bill due on 10 Nov");
new Reminder(email).send("asha@mail.in", "electricity bill due on 10 Nov");
}
}
Main.java:18: error: channel has private access in Message
void send(String to, String text) { channel.deliver(to, "ALERT: " + text.toUpperCase()); } }
^
Main.java:20: error: channel has private access in Message
void send(String to, String text) { channel.deliver(to, "Reminder: " + text); } }
^
2 errors
Use protected (visible to subclasses), or keep it private and give Message a protected void deliver(String to, String text) helper that subclasses call.
8. Bridge vs Strategy
Both look the same in code: a class holding an interface in a field. The intent is different.
| Bridge | Strategy | |
|---|---|---|
| Category | Structural | Behavioural (episode 34) |
| What varies | Both sides are families that keep growing | One algorithm is swapped |
| Example | Message × Channel, Shape × Renderer |
Checkout with a swappable Discount rule |
| When designed | Up front, as the shape of the design | Whenever one step needs alternatives |
Rule of thumb: if only one side varies, it's a strategy. If both sides are hierarchies that grow, it's a bridge.
9. Bridge vs Adapter, and when to use a bridge
- A bridge is designed up front: you split the two sides before classes multiply.
- An adapter (episode 27) is fitted afterwards: it makes an existing class match an interface it was never written for.
Use a bridge when two ideas vary separately: message and channel, shape and renderer, report and file format, remote control and device. Skip it when there is only one implementation and there always will be: a plain class is enough. That's YAGNI ("you aren't gonna need it", episode 17).
Common mistakes
| Mistake | Exact message / symptom | Why | Fix |
|---|---|---|---|
| One subclass per combination | no error: SMS REJECTED: 40 chars, limit 30 |
A fix was copied into only one class | Split into two hierarchies |
Subclass constructor skips super(c) |
error: constructor Message in class Message cannot be applied to given types; |
Message needs a Channel |
Alert(Channel c) { super(c); } |
Bridge field is private |
error: channel has private access in Message |
Subclasses can't see it | protected, or a protected helper |
| Abstraction checks the channel type | no error: if (channel instanceof Sms) ... |
The two sides are glued again | Put channel rules inside the channel |
| A bridge for a single implementation | no error: extra classes to read | Nothing varies | A plain class (YAGNI) |
Mini project: reports and formats
A tool makes three kinds of report (sales, stock, tax) in several file formats. Build it with a bridge: Report (abstraction) holds a Format (implementor). Each report builds its own title and rows; each format decides how to write them. Print a sales report as CSV and a tax report as HTML.
Solution
import java.util.List;
interface Format { String write(String title, List<String> rows); } // implementor
class Csv implements Format {
public String write(String title, List<String> rows) { return title + "\n" + String.join("\n", rows); }
}
class Html implements Format {
public String write(String title, List<String> rows) {
StringBuilder sb = new StringBuilder("<h1>" + title + "</h1>\n<ul>\n");
for (String r : rows) sb.append(" <li>").append(r).append("</li>\n");
return sb.append("</ul>").toString();
}
}
abstract class Report { // abstraction
protected final Format format;
Report(Format format) { this.format = format; }
abstract String render();
}
class SalesReport extends Report {
SalesReport(Format f) { super(f); }
String render() { return format.write("Sales", List.of("chai,120", "samosa,80")); }
}
class TaxReport extends Report {
TaxReport(Format f) { super(f); }
String render() { return format.write("Tax", List.of("GST collected: Rs 1,450")); }
}
public class Main {
public static void main(String[] args) {
System.out.println(new SalesReport(new Csv()).render());
System.out.println(new TaxReport(new Html()).render());
}
}
Sales
chai,120
samosa,80
<h1>Tax</h1>
<ul>
<li>GST collected: Rs 1,450</li>
</ul>
Adding a Pdf format or a StockReport is one class each. String.join("\n", rows) joins the rows with new lines; StringBuilder builds a string piece by piece without making a new string each time.
Practice
1. Kinds: Alert, Reminder, Promo, Otp. Channels: SMS, Email, Push. How many classes with one subclass per pair, and with a bridge?
Answer
One subclass per pair: 4 × 3 = 12. Bridge: 4 + 3 = 7 (plus the Message and Channel types themselves).
2. Add a Chat channel to the bridge version. Which existing classes change?
Answer
None. Write class Chat implements Channel { ... }. Every message kind can use it at once: new Alert(new Chat()).
3. Why is instanceof Sms inside Alert.send a bad idea?
Answer
The abstraction would know about a concrete implementor, so adding or changing a channel means editing message classes again: the two sides are coupled. Channel-specific rules (like the 30-character limit) belong inside that channel.
4. A Logger has one ConsoleOutput, and only the log level changes. Bridge or strategy?
Answer
Neither needs a full bridge: only one side varies. If the output really must be swappable, that's a strategy (one interface, swappable at runtime). A bridge needs two families that both grow.
5. Rewrite Message so its field is private but subclasses still work.
Answer
abstract class Message {
private final Channel channel;
Message(Channel channel) { this.channel = channel; }
protected void deliver(String to, String text) { channel.deliver(to, text); }
abstract void send(String to, String text);
}
// in Alert: void send(String to, String text) { deliver(to, "ALERT: " + text.toUpperCase()); }
Quick quiz
String[] reports = {"Sales", "Stock", "Tax"}; // 3 kinds
String[] formats = {"PDF", "Excel", "CSV", "HTML"}; // 4 formats
// With a bridge: how many Report + Format classes?
(a) 12 (b) 7 (c) 4 (d) 3
Answer
(b) 7: three report classes plus four format classes. One subclass per pair would need 3 × 4 = 12, and a fifth format would cost three more classes instead of one.
Interview questions
- What is the Bridge pattern? A structural pattern that splits a class into two hierarchies, an abstraction and an implementation, joined by composition, so the two can vary independently.
- What problem does it solve? The class explosion (m × n subclasses) you get when two independent dimensions are combined through inheritance, and the duplicated code that comes with it.
- Participants? Abstraction, refined abstraction, implementor, concrete implementor.
- Where is "the bridge"? The reference (field) from the abstraction to the implementor.
- Bridge vs Strategy? Same structure; Bridge is structural and both sides are growing hierarchies; Strategy is behavioural and swaps one algorithm in one context.
- Bridge vs Adapter? Bridge is designed up front to keep two sides apart; Adapter is applied afterwards to make an existing class fit an interface.
- How does Bridge relate to "composition over inheritance"? It replaces one dimension of inheritance with composition (episode 11).
- Can the implementation change at runtime? Yes: inject a different implementor (or add a setter), as with the channel picked from a setting.
- Examples? Messages × channels, shapes × renderers, remote controls × devices, reports × file formats.
- Downside? More indirection and more types; not worth it when only one side ever varies.
Glossary
| Term | Meaning, with an example |
|---|---|
| Structural pattern | A pattern about how classes and objects are combined into bigger structures. Adapter, Facade, Bridge |
| Bridge pattern | Split a design into two hierarchies joined by a field. Message holds a Channel |
| Abstraction (in Bridge) | The high-level, what side the client talks to. Message |
| Refined abstraction | A subclass of the abstraction adding its own behaviour. Alert, Reminder |
| Implementor | The interface for the low-level, how work. Channel |
| Concrete implementor | A class that implements the implementor. Sms, Email |
| Implementation (in Bridge) | The low-level side that does the work: the implementor and its classes |
| The bridge | The has-a field from abstraction to implementor. protected final Channel channel |
| Decouple | Remove the hard link between two things so each can change alone |
| Vary independently | Each side can gain new classes without changing the other |
| Class explosion | The number of classes multiplying (m × n) as either side grows |
| Hierarchy | A family of classes related by inheritance: a parent and its subclasses |
| Inheritance | A class taking on another class's fields and methods with extends |
| Composition / has-a | An object holding another object in a field |
| Delegation | Handing work to another object. channel.deliver(...) |
| Compile time / runtime | When the code is compiled / while the program runs |
| Interface | A list of methods a class promises to have. interface Channel |
| Abstract class | A class that can't be created with new itself; subclasses fill in its abstract methods. Message |
super(c) |
Calls the parent class's constructor with c |
protected |
Visible to the class, its subclasses and its package |
private |
Visible only inside the class itself |
| Ternary operator | cond ? a : b: a if cond is true, else b |
Map.of / List.of |
Make small unmodifiable maps and lists |
| Renderer | Code that actually draws a shape |
| Vector / pixels | Drawing with lines and curves / with individual dots on a screen |
| Strategy pattern | Swap one algorithm inside one context class (episode 34) |
| Adapter pattern | Make an existing class fit an interface it wasn't written for (episode 27) |
| YAGNI | "You aren't gonna need it": don't build what you don't need yet |
| SMS gateway | The company service that actually sends text messages |
Summary
- One subclass per combination of two ideas gives a class explosion (m × n) and copied code where fixes go missing.
- The Bridge splits the design into two hierarchies: the abstraction has an implementor. Classes add (m + n) instead of multiply.
- Roles: abstraction, refined abstraction, implementor, concrete implementor; the field between them is the bridge.
- The pair can be chosen at runtime.
- Bridge: both sides grow. Strategy: one algorithm swaps. Adapter: fitted afterwards.
Next episode: The Composite pattern.