Pular para o conteúdo
  1. Atlas
  2. GoF

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

Fluxo
5/5
Abstração: o que dizerImplementação: por ondeAbstractPaymentNotifierNotifierPaymentSimpleNotifierPaymentDetailedInterfaceNotificationChannelChannelNotificationSmscorta em 160ChannelNotificationEmailcompõeimplementaimplementa
5

5 passos — reproduza para seguir o 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. 1

    InterfaceNotificationChannel: um deliver(subject, body)

  2. 2

    AbstractPaymentNotifier recebe o canal e delega — a ponte é essa referência

  3. 3

    NotifierPaymentSimple e NotifierPaymentDetailed decidem só o texto

  4. 4

    Qualquer aviso com qualquer canal em tempo de execução

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

  1. 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}`);
  }
}

Por que se relacionam

Teste rápido

Qual destes combina com Bridge?

Próximo projeto, GoFBuilder
Esc

↑ ↓ navegarEnter abrir239 resultados