pattern/gof/bridge
Bridge
Separa duas dimensões independentes (o que se diz × por onde) em duas hierarquias ligadas por composição: N + M classes em vez de N × M.
- passos
- 4
- arquivos
- 4
- testes
- 0
- tecnologias
- 2
Cenário
Confirmação de PIX simples ou detalhada, por SMS (corta em 160 caracteres) ou e-mail.
Planta
Fluxo5 passos — reproduza para seguir o fluxo
- chamada
- resposta ou assíncrono
- falha
- passo
- toque num nó para focar
- Outras plantas de fluxo
Como funciona
4passos
Separa duas dimensões independentes (o que se diz × por onde) em duas hierarquias ligadas por composição
Esconde cada passo: lembre antes de tocar para revelar.
- 1
InterfaceNotificationChannel: umdeliver(subject, body) - 2
AbstractPaymentNotifierrecebe o canal e delega — a ponte é essa referência - 3
NotifierPaymentSimpleeNotifierPaymentDetaileddecidem só o texto - 4
Qualquer aviso com qualquer canal em tempo de execução
Trade-offs
O que se ganha, o que se paga
Vantagens
N + M classes em vez de N × M
Canal e aviso evoluem separados
Custos
Duas hierarquias e uma indireção
Excesso com uma dimensão só (use Strategy)
Código
pattern/gof/bridge
4 arquivos./
- package.jsoninfra
- README.md
- tsconfig.jsoninfra
src/
- demo.tsdemo
Executar só Bun
bun run demo# roda o cenário
Saída: quatro combinações aviso × canal com 2 + 2 classes; o e-mail leva assunto e corpo, o SMS só o corpo.
- Requisitos
- Bun
Código
src/demo.ts
// Demo: payment notifier (what to say) × notification channel (where to say it), combined at runtime by composition.
type Delivery = { channel: string; content: string };
// Implementation side: how a message reaches the customer. A new channel is a new class, nothing else changes.
interface InterfaceNotificationChannel {
deliver(subject: string, body: string): Delivery;
}
// One SMS segment; above it the operator splits and charges per part, so the channel cuts the text itself.
const SMS_SEGMENT_LENGTH = 160;
class ChannelNotificationSms implements InterfaceNotificationChannel {
deliver(_subject: string, body: string): Delivery {
return { channel: "sms", content: body.length <= SMS_SEGMENT_LENGTH ? body : `${body.slice(0, SMS_SEGMENT_LENGTH - 1)}…` };
}
}
class ChannelNotificationEmail implements InterfaceNotificationChannel {
deliver(subject: string, body: string): Delivery {
return { channel: "email", content: `Subject: ${subject} | ${body}` };
}
}
// Abstraction side: holds a channel and delegates to it — the bridge is this reference, never inheritance.
type EventPayment = { transactionId: string; amountCents: number; payeeName: string; receiptUrl: string };
const brl = (cents: number) => `R$ ${(cents / 100).toFixed(2)}`;
abstract class AbstractPaymentNotifier {
constructor(protected readonly channel: InterfaceNotificationChannel) {}
abstract notify(event: EventPayment): Delivery;
}
class NotifierPaymentSimple extends AbstractPaymentNotifier {
notify(event: EventPayment): Delivery {
return this.channel.deliver("PIX confirmed", `PIX of ${brl(event.amountCents)} to ${event.payeeName} confirmed.`);
}
}
class NotifierPaymentDetailed extends AbstractPaymentNotifier {
notify(event: EventPayment): Delivery {
return this.channel.deliver(`Receipt ${event.transactionId}`, `PIX ${event.transactionId} of ${brl(event.amountCents)} to ${event.payeeName}, settled. Receipt: ${event.receiptUrl}`);
}
}
const payment: EventPayment = { transactionId: "E60701190202609291830ABCDEF12", amountCents: 345_090, payeeName: "Imobiliaria Central", receiptUrl: "https://banco.example/receipts/E60701190202609291830ABCDEF12" };
// 2 notifiers + 2 channels = 4 classes for 4 combinations; a 3rd channel is 1 class, not 2.
for (const notifier of [NotifierPaymentSimple, NotifierPaymentDetailed]) {
for (const channel of [new ChannelNotificationSms(), new ChannelNotificationEmail()]) {
const delivery = new notifier(channel).notify(payment);
console.log(` [${notifier.name} → ${delivery.channel}] ${delivery.content}`);
}
}
Nível
introdutório
1/13
- Linhas de TypeScript
- 43
- Tipo
- A — código puro
Domínio financeiro
- PIX
Padrões do catálogo que implementa
- Bridge
Trilhapasso 2 de 7
GoF — estrutura
Por que se relacionam
Combina com
Alternativa a
Teste rápido
Qual destes combina com Bridge?
Implementação trocável atrás da abstração. Abrir Strategy
Seu progresso
0/157 estudados
Fica salvo só neste navegador.