Most (Bridge) – dwie osie zmian bez eksplozji klas
Most rozdziela abstrakcję (co robimy) od implementacji (jak to robimy), tak by obie hierarchie rozwijały się niezależnie. Przykład powiadomień i kanałów dostarczania w C#, TypeScript, Javie, Go i Pythonie.
Most to wzorzec, który brzmi najbardziej abstrakcyjnie z całego katalogu, a rozwiązuje bardzo przyziemny problem: hierarchię klas, która rośnie w dwóch kierunkach naraz. Most (ang. Bridge) dzieli ją na dwie niezależne hierarchie połączone referencją – „mostem” – zamiast dziedziczenia.
Problem: EmailUrgentAlert, SmsUrgentAlert, PushUrgentAlert…
Pierogarnia wysyła klientom powiadomienia. Są pilne alerty (nieudana płatność) i przypomnienia (zamówienie dotrze za 30 minut). Każde może pójść e-mailem albo SMS-em. Pierwszy projekt opierał się na dziedziczeniu:
class EmailAlert extends EmailSender { /* urgent formatting + email */ }
class SmsAlert extends SmsSender { /* urgent formatting again + SMS */ }
class EmailReminder extends EmailSender { /* reminder formatting + email */ }
class SmsReminder extends SmsSender { /* reminder formatting again + SMS */ }
// next sprint: PushAlert, PushReminder… and a third kind of noticeCztery klasy to jeszcze nic. Ale dział marketingu chce powiadomień push i komunikatora, a produkt – trzeciego rodzaju wiadomości (podsumowanie dnia). Formatowanie alertu jest skopiowane w każdej klasie „…Alert”, a obsługa limitu 160 znaków – w każdej „Sms…”. Każda zmiana w jednym wymiarze wymaga edycji wielu klas.
| Dziedziczenie | Most | |
|---|---|---|
| 1 kanał | 4 klas | 5 klas |
| 2 kanały | 8 klas | 6 klas |
| 3 kanały | 12 klas | 7 klas |
| 4 kanały | 16 klas | 8 klas |
| 5 kanałów | 20 klas | 9 klas |
| 6 kanałów | 24 klas | 10 klas |
Rozwiązanie: dwie hierarchie i referencja między nimi
Rozpoznajemy dwa niezależne wymiary. Abstrakcja odpowiada na pytanie co komunikujemy: Notice z podklasami Alert i Reminder – to tu żyje formatowanie i logika danego rodzaju wiadomości. Implementator odpowiada na pytanie jak to dostarczamy: interfejs Channel z implementacjami EmailChannel i SmsChannel – to tu żyją szczegóły transportu, np. limit długości SMS-a. Abstrakcja dostaje kanał w konstruktorze i deleguje do niego wysyłkę.
| Rola | W przykładzie | Odpowiedzialność |
|---|---|---|
| Abstrakcja (Abstraction) | Notice | interfejs wysokiego poziomu dla klienta, trzyma implementatora |
| Abstrakcja rozszerzona | Alert, Reminder | warianty logiki „co” |
| Implementator (Implementor) | Channel | prymitywne operacje, z których korzysta abstrakcja |
| Implementator konkretny | EmailChannel, SmsChannel | warianty „jak” – konkretne platformy, protokoły, biblioteki |
Ważna różnica względem zwykłego wstrzykiwania zależności: interfejs implementatora jest zwykle niższego poziomu niż interfejs abstrakcji. Kanał umie tylko „dostarcz tytuł i treść do odbiorcy”; to abstrakcja wie, że alert ma być pisany wielkimi literami, a przypomnienie zawiera czas do dostawy.
Implementacja w pięciu językach
W językach z klasami abstrakcja jest klasą abstrakcyjną z polem channel. W Go zamiast hierarchii są dwie struktury z polem typu Channel – most to po prostu pole interfejsowe, a dziedziczenie nie jest do niczego potrzebne.
Notice + Channel
new Alert(new SmsChannel()).Notify("Ola", "Payment for order 1042 failed");
new Reminder(new EmailChannel(), TimeSpan.FromMinutes(30)).Notify("Ola", "Your pierogi arrive soon");
// Implementor: how a message travels.
public interface IChannel
{
void Deliver(string recipient, string title, string body);
}
public sealed class EmailChannel : IChannel
{
public void Deliver(string recipient, string title, string body) =>
Console.WriteLine($"[email to {recipient}] Subject: {title} | {body}");
}
public sealed class SmsChannel : IChannel
{
// SMS has no subject line and a hard length limit.
public void Deliver(string recipient, string title, string body)
{
var text = $"{title}: {body}";
Console.WriteLine($"[sms to {recipient}] {(text.Length > 160 ? text[..157] + "..." : text)}");
}
}
// Abstraction: what the message means. It holds a channel instead of inheriting one.
public abstract class Notice(IChannel channel)
{
protected IChannel Channel { get; } = channel;
public abstract void Notify(string recipient, string text);
}
public sealed class Alert(IChannel channel) : Notice(channel)
{
public override void Notify(string recipient, string text) =>
Channel.Deliver(recipient, "URGENT", text.ToUpperInvariant());
}
public sealed class Reminder(IChannel channel, TimeSpan lead) : Notice(channel)
{
public override void Notify(string recipient, string text) =>
Channel.Deliver(recipient, $"Reminder, {lead.TotalMinutes:0} min left", text);
}// Implementor: how a message travels.
interface Channel {
deliver(recipient: string, title: string, body: string): void;
}
class EmailChannel implements Channel {
deliver(recipient: string, title: string, body: string): void {
console.log(`[email to ${recipient}] Subject: ${title} | ${body}`);
}
}
class SmsChannel implements Channel {
// SMS has no subject line and a hard length limit.
deliver(recipient: string, title: string, body: string): void {
const text = `${title}: ${body}`;
console.log(`[sms to ${recipient}] ${text.length > 160 ? text.slice(0, 157) + "..." : text}`);
}
}
// Abstraction: what the message means. It holds a channel instead of inheriting one.
abstract class Notice {
constructor(protected readonly channel: Channel) {}
abstract notify(recipient: string, text: string): void;
}
class Alert extends Notice {
notify(recipient: string, text: string): void {
this.channel.deliver(recipient, "URGENT", text.toUpperCase());
}
}
class Reminder extends Notice {
constructor(channel: Channel, private readonly leadMinutes: number) {
super(channel);
}
notify(recipient: string, text: string): void {
this.channel.deliver(recipient, `Reminder, ${this.leadMinutes} min left`, text);
}
}
new Alert(new SmsChannel()).notify("Ola", "Payment for order 1042 failed");
new Reminder(new EmailChannel(), 30).notify("Ola", "Your pierogi arrive soon");import java.time.Duration;
// Implementor: how a message travels.
interface Channel {
void deliver(String recipient, String title, String body);
}
class EmailChannel implements Channel {
public void deliver(String recipient, String title, String body) {
System.out.printf("[email to %s] Subject: %s | %s%n", recipient, title, body);
}
}
class SmsChannel implements Channel {
// SMS has no subject line and a hard length limit.
public void deliver(String recipient, String title, String body) {
String text = title + ": " + body;
System.out.printf("[sms to %s] %s%n", recipient, text.length() > 160 ? text.substring(0, 157) + "..." : text);
}
}
// Abstraction: what the message means. It holds a channel instead of inheriting one.
abstract class Notice {
protected final Channel channel;
protected Notice(Channel channel) { this.channel = channel; }
abstract void notify(String recipient, String text);
}
class Alert extends Notice {
Alert(Channel channel) { super(channel); }
void notify(String recipient, String text) { channel.deliver(recipient, "URGENT", text.toUpperCase()); }
}
class Reminder extends Notice {
private final Duration lead;
Reminder(Channel channel, Duration lead) { super(channel); this.lead = lead; }
void notify(String recipient, String text) {
channel.deliver(recipient, "Reminder, " + lead.toMinutes() + " min left", text);
}
}
public class Notifications {
public static void main(String[] args) {
new Alert(new SmsChannel()).notify("Ola", "Payment for order 1042 failed");
new Reminder(new EmailChannel(), Duration.ofMinutes(30)).notify("Ola", "Your pierogi arrive soon");
}
}package main
import (
"fmt"
"strings"
"time"
)
// Channel is the implementor: how a message travels.
type Channel interface {
Deliver(recipient, title, body string)
}
type EmailChannel struct{}
func (EmailChannel) Deliver(recipient, title, body string) {
fmt.Printf("[email to %s] Subject: %s | %s\n", recipient, title, body)
}
// SmsChannel has no subject line and a hard length limit.
type SmsChannel struct{}
func (SmsChannel) Deliver(recipient, title, body string) {
text := title + ": " + body
if len(text) > 160 {
text = text[:157] + "..."
}
fmt.Printf("[sms to %s] %s\n", recipient, text)
}
// Alert and Reminder are refined abstractions: what the message means.
// Each holds a Channel instead of being tied to one.
type Alert struct{ Channel Channel }
func (a Alert) Notify(recipient, text string) {
a.Channel.Deliver(recipient, "URGENT", strings.ToUpper(text))
}
type Reminder struct {
Channel Channel
Lead time.Duration
}
func (r Reminder) Notify(recipient, text string) {
title := fmt.Sprintf("Reminder, %.0f min left", r.Lead.Minutes())
r.Channel.Deliver(recipient, title, text)
}
func main() {
Alert{Channel: SmsChannel{}}.Notify("Ola", "Payment for order 1042 failed")
Reminder{Channel: EmailChannel{}, Lead: 30 * time.Minute}.Notify("Ola", "Your pierogi arrive soon")
}from abc import ABC, abstractmethod
from datetime import timedelta
from typing import Protocol
class Channel(Protocol):
"""Implementor: how a message travels."""
def deliver(self, recipient: str, title: str, body: str) -> None: ...
class EmailChannel:
def deliver(self, recipient: str, title: str, body: str) -> None:
print(f"[email to {recipient}] Subject: {title} | {body}")
class SmsChannel:
def deliver(self, recipient: str, title: str, body: str) -> None:
# SMS has no subject line and a hard length limit.
text = f"{title}: {body}"
print(f"[sms to {recipient}] {text if len(text) <= 160 else text[:157] + '...'}")
class Notice(ABC):
"""Abstraction: what the message means. It holds a channel instead of inheriting one."""
def __init__(self, channel: Channel) -> None:
self.channel = channel
@abstractmethod
def notify(self, recipient: str, text: str) -> None: ...
class Alert(Notice):
def notify(self, recipient: str, text: str) -> None:
self.channel.deliver(recipient, "URGENT", text.upper())
class Reminder(Notice):
def __init__(self, channel: Channel, lead: timedelta) -> None:
super().__init__(channel)
self.lead = lead
def notify(self, recipient: str, text: str) -> None:
minutes = int(self.lead.total_seconds() // 60)
self.channel.deliver(recipient, f"Reminder, {minutes} min left", text)
if __name__ == "__main__":
Alert(SmsChannel()).notify("Ola", "Payment for order 1042 failed")
Reminder(EmailChannel(), timedelta(minutes=30)).notify("Ola", "Your pierogi arrive soon")Dalsza część artykułu dla zalogowanych
Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:
- Krok po kroku
- Kiedy stosować, a kiedy nie
- Powiązania z innymi wzorcami
- W praktyce
- Szybki test
- Podsumowanie