Card 04/ 08
Bridge Example: Notifications by Urgency and by Channel
Urgent and routine messages, each sent by email, SMS or push, without a class per pair.
Notifications that vary by urgency and by channel are a natural Bridge, and this example maps the template onto it. A routine notification is sent once. An urgent one is sent twice, the second time as a reminder. Either can go by email, by SMS, which cuts the text to 30 characters, or by push.
| Template | Notifications example |
|---|---|
| Abstraction | Notification, which holds a channel and sends once |
| RefinedAbstraction | UrgentNotification, which sends the message and a reminder |
| Implementor | Channel, with deliver |
| ConcreteImplementor | Email, Sms and Push |
from abc import ABC, abstractmethod
class Channel(ABC):
@abstractmethod
def deliver(self, recipient: str, text: str) -> None: ...
class Email(Channel):
def deliver(self, recipient: str, text: str) -> None:
print(f"email to {recipient}: {text}")
class Sms(Channel):
def deliver(self, recipient: str, text: str) -> None:
print(f"sms to {recipient}: {text[:30]}")
class Push(Channel):
def deliver(self, recipient: str, text: str) -> None:
print(f"push to {recipient}: {text}")
class Notification:
def __init__(self, channel: Channel) -> None:
self._channel = channel
def send(self, recipient: str, text: str) -> None:
self._channel.deliver(recipient, text)
class UrgentNotification(Notification):
def send(self, recipient: str, text: str) -> None:
self._channel.deliver(recipient, f"URGENT {text}")
self._channel.deliver(recipient, f"URGENT reminder: {text}")
Notification(Email()).send("ana", "Your invoice is ready")
UrgentNotification(Sms()).send("ben", "Server db-2 is down since 02:14 UTC")
UrgentNotification(Push()).send("ben", "Server db-2 is down")
kinds, channels = 2, 3
print(f"one subclass per pair: {kinds * channels}, with a bridge: {kinds + channels}")
kinds, channels = 2, 4
print(f"after a fourth channel: {kinds * channels} against {kinds + channels}")email to ana: Your invoice is ready
sms to ben: URGENT Server db-2 is down sin
sms to ben: URGENT reminder: Server db-2 i
push to ben: URGENT Server db-2 is down
push to ben: URGENT reminder: Server db-2 is down
one subclass per pair: 6, with a bridge: 5
after a fourth channel: 8 against 6The urgent message by SMS shows both sides at work: the abstraction sent it twice, and the channel cut each copy to 30 characters. Neither class knows about the other's rule.
| Channels | One subclass per pair | With a bridge |
|---|---|---|
| 3 | 6 | 5 |
| 4 | 8 | 6 |
| 5 | 10 | 7 |
The first two rows are the listing's own last lines. Each new channel costs two classes without a bridge, one per kind of notification, and one class with it. A third kind, such as a digest that batches messages, would cost one class per channel without a bridge, and one with it.
← → move through sections and cards