Design Patterns

Pattern 7 of 23, Structural family

Bridge

Also known as: Handle/Body

Decouple an abstraction from its implementation so that the two can evolve independently.

The problem

You have Normal / Urgent notifications and SMS / Email / Slack channels. With inheritance you end up with UrgentSms, UrgentEmailโ€ฆ: N ร— M classes.

The solution

Replace inheritance with composition: the abstraction (Notification) holds a reference to an implementation (Sender). The two hierarchies grow separately.

The pattern in action

  • Client
  • Key role of the pattern
  • Object
  • Data or state
  1. The application uses the abstraction.
  2. The abstraction delegates to the implementation it references: that is the "bridge".
  3. The implementation is swapped at runtime.
  4. App โ†’ UrgentNotification: notify("Server down")
  5. Same abstraction, different channel: N types ร— M channels without Nร—M subclasses.

An analogy

A remote control (abstraction) and the devices (TV, radio): you can build a new remote without touching the devices, and vice versa.

When to use it

  • Two independent dimensions of variation
  • Switching implementations at runtime
  • Cross-platform code (drivers, rendering engines)

Pros and cons

Pros

  • Avoids a combinatorial explosion of subclasses
  • Open/Closed on both axes
  • Implementation details hidden from the client

Cons

  • More abstract to grasp at first
  • Pointless when there is only one dimension of variation

Implementations

The same example, written idiomatically in each language.

Bridge in Python

bridge.py 28 lines
from abc import ABC, abstractmethod


class Sender(ABC):                      # implementation side
    @abstractmethod
    def send(self, text: str) -> None: ...

class SmsSender(Sender):
    def send(self, text): print(f"SMS: {text}")

class EmailSender(Sender):
    def send(self, text): print(f"EMAIL: {text}")


class Notification:                     # abstraction side
    def __init__(self, sender: Sender):
        self.sender = sender            # the bridge

    def notify(self, msg: str):
        self.sender.send(msg)

class UrgentNotification(Notification):
    def notify(self, msg: str):
        self.sender.send(f"[URGENT] {msg}")


UrgentNotification(SmsSender()).notify("Server down")
UrgentNotification(EmailSender()).notify("Server down")

Bridge in TypeScript

bridge.ts 19 lines
interface Sender { send(text: string): void; }

class SmsSender implements Sender { send(t: string) { console.log("SMS:", t); } }
class EmailSender implements Sender { send(t: string) { console.log("EMAIL:", t); } }

abstract class Notification {
  constructor(protected sender: Sender) {} // the bridge
  abstract notify(msg: string): void;
}

class NormalNotification extends Notification {
  notify(msg: string) { this.sender.send(msg); }
}
class UrgentNotification extends Notification {
  notify(msg: string) { this.sender.send("[URGENT] " + msg); }
}

new UrgentNotification(new SmsSender()).notify("Server down");
new NormalNotification(new EmailSender()).notify("Report ready");

Bridge in Java

bridge.java 21 lines
interface Sender { void send(String text); }

class SmsSender implements Sender {
    public void send(String t) { System.out.println("SMS: " + t); }
}
class EmailSender implements Sender {
    public void send(String t) { System.out.println("EMAIL: " + t); }
}

abstract class Notification {
    protected final Sender sender;              // the bridge
    Notification(Sender sender) { this.sender = sender; }
    abstract void alert(String msg);            // (notify() is reserved by Object)
}

class UrgentNotification extends Notification {
    UrgentNotification(Sender s) { super(s); }
    void alert(String msg) { sender.send("[URGENT] " + msg); }
}

new UrgentNotification(new SmsSender()).alert("Server down");

Bridge in C#

bridge.cs 17 lines
interface ISender { void Send(string text); }

class SmsSender : ISender { public void Send(string t) => Console.WriteLine($"SMS: {t}"); }
class EmailSender : ISender { public void Send(string t) => Console.WriteLine($"EMAIL: {t}"); }

abstract class Notification(ISender sender)
{
    protected ISender Sender { get; } = sender;   // the bridge
    public abstract void Notify(string msg);
}

class UrgentNotification(ISender s) : Notification(s)
{
    public override void Notify(string msg) => Sender.Send($"[URGENT] {msg}");
}

new UrgentNotification(new SmsSender()).Notify("Server down");

Bridge in PHP

bridge.php 26 lines
interface Sender { public function send(string $text): void; }

class SmsSender implements Sender
{
    public function send(string $t): void { echo "SMS: $t", PHP_EOL; }
}
class EmailSender implements Sender
{
    public function send(string $t): void { echo "EMAIL: $t", PHP_EOL; }
}

abstract class Notification
{
    public function __construct(protected Sender $sender) {}   // the bridge
    abstract public function notify(string $msg): void;
}

class UrgentNotification extends Notification
{
    public function notify(string $msg): void
    {
        $this->sender->send("[URGENT] $msg");
    }
}

(new UrgentNotification(new SmsSender()))->notify('Server down');

Bridge in Go

bridge.go 20 lines
type Sender interface{ Send(text string) }

type SmsSender struct{}

func (SmsSender) Send(t string) { fmt.Println("SMS:", t) }

type EmailSender struct{}

func (EmailSender) Send(t string) { fmt.Println("EMAIL:", t) }

type UrgentNotification struct {
    Sender Sender // the bridge
}

func (n UrgentNotification) Notify(msg string) {
    n.Sender.Send("[URGENT] " + msg)
}

UrgentNotification{SmsSender{}}.Notify("Server down")
UrgentNotification{EmailSender{}}.Notify("Server down")

Frequently asked questions

What is the Bridge design pattern?

Decouple an abstraction from its implementation so that the two can evolve independently. Replace inheritance with composition: the abstraction (Notification) holds a reference to an implementation (Sender). The two hierarchies grow separately.

When should you use the Bridge pattern?

Two independent dimensions of variation; Switching implementations at runtime; Cross-platform code (drivers, rendering engines).

What are the pros and cons of the Bridge pattern?

Pros: Avoids a combinatorial explosion of subclasses; Open/Closed on both axes; Implementation details hidden from the client. Cons: More abstract to grasp at first; Pointless when there is only one dimension of variation.