Bridge
En français : Pont
Séparer une abstraction de son implémentation pour que les deux puissent évoluer indépendamment.
- 5 étapes animées
- 6 langages
- Patterns de structure
Le problème
Tu as des notifications Normal / Urgent et des canaux SMS / Email / Slack. Par héritage, tu obtiens UrgentSms, UrgentEmail… : N × M classes.
La solution
Remplacer l'héritage par la composition : l'abstraction (Notification) contient une référence vers une implémentation (Sender). Les deux hiérarchies grandissent séparément.
Le pattern en action
- Client
- Rôle clé du pattern
- Objet
- Données ou état
- L'application utilise l'abstraction.
- L'abstraction délègue à l'implémentation qu'elle référence : c'est le « pont ».
- On change d'implémentation à l'exécution.
- App → UrgentNotification : notify("Serveur down")
- Même abstraction, autre canal : N types × M canaux sans N×M sous-classes.
Une analogie
Une télécommande (abstraction) et les appareils (TV, radio) : on peut créer une nouvelle télécommande sans toucher aux appareils, et inversement.
Quand l'utiliser
- Deux dimensions de variation indépendantes
- Changer d'implémentation à l'exécution
- Code multi-plateforme (drivers, moteurs de rendu)
Avantages et limites
Avantages
- Évite l'explosion combinatoire de sous-classes
- Open/Closed sur les deux axes
- Détails d'implémentation cachés au client
Limites
- Plus abstrait à comprendre au premier abord
- Inutile s'il n'y a qu'une seule dimension de variation
Implémentations
Le même exemple, écrit de façon idiomatique dans chaque langage.
Bridge en Python
from abc import ABC, abstractmethod
class Sender(ABC): # côté implémentation
@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: # côté abstraction
def __init__(self, sender: Sender):
self.sender = sender # le pont
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("Serveur down")
UrgentNotification(EmailSender()).notify("Serveur down")
Bridge en TypeScript
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) {} // le pont
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("Serveur down");
new NormalNotification(new EmailSender()).notify("Rapport prêt");
Bridge en Java
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; // le pont
Notification(Sender sender) { this.sender = sender; }
abstract void alert(String msg); // (notify() est réservé par Object)
}
class UrgentNotification extends Notification {
UrgentNotification(Sender s) { super(s); }
void alert(String msg) { sender.send("[URGENT] " + msg); }
}
new UrgentNotification(new SmsSender()).alert("Serveur down");
Bridge en C#
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; // le pont
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("Serveur down");
Bridge en PHP
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) {} // le pont
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('Serveur down');
Bridge en Go
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 // le pont
}
func (n UrgentNotification) Notify(msg string) {
n.Sender.Send("[URGENT] " + msg)
}
UrgentNotification{SmsSender{}}.Notify("Serveur down")
UrgentNotification{EmailSender{}}.Notify("Serveur down")
Questions fréquentes
Qu'est-ce que le design pattern Bridge ?
Séparer une abstraction de son implémentation pour que les deux puissent évoluer indépendamment. Remplacer l'héritage par la composition : l'abstraction (Notification) contient une référence vers une implémentation (Sender). Les deux hiérarchies grandissent séparément.
Quand utiliser le pattern Bridge ?
Deux dimensions de variation indépendantes ; Changer d'implémentation à l'exécution ; Code multi-plateforme (drivers, moteurs de rendu).
Quels sont les avantages et les inconvénients du pattern Bridge ?
Avantages : Évite l'explosion combinatoire de sous-classes ; Open/Closed sur les deux axes ; Détails d'implémentation cachés au client. Limites : Plus abstrait à comprendre au premier abord ; Inutile s'il n'y a qu'une seule dimension de variation.