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

Abstract Factory

Uma fábrica por família cria objetos relacionados que precisam combinar entre si; o cliente conhece só a interface da fábrica e nunca mistura famílias. Use quando um contexto (país, marca, ambiente) troca vários objetos de uma vez.

passos
4
arquivos
4
testes
0
tecnologias
2

Cenário

O mesmo checkout transfere R$ 1.500,00 no Brasil (PIX, reais, BACEN) e $1,500.00 no México (SPEI, pesos, Banxico) sem nenhum if por país.

Planta

Fluxo
9/9
transferProcessInterfaceFactoryRegionFactoryRegionBrazilFactoryRegionMexicoPIXFormatador BRLRelatório BACENSPEIFormatador MXNRelatório Banxico
9

9 passos — reproduza para seguir o fluxo

Como funciona

4passos

Uma fábrica por família cria objetos relacionados que precisam combinar entre si

Esconde cada passo: lembre antes de tocar para revelar.

  1. 1

    InterfaceFactoryRegion tem um método por produto: paymentCreate, formatterCreate, reporterCreate

  2. 2

    FactoryRegionBrazil e FactoryRegionMexico criam famílias coerentes

  3. 3

    transferProcess usa só a interface da fábrica

  4. 4

    A região é escolhida uma vez, na raiz de composição

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Famílias sempre coerentes, sem mistura

  • Região nova = fábrica nova, cliente intacto

Custos

  • Produto novo muda todas as fábricas

  • Muitas classes para poucas variações

Código

pattern/gof/abstract-factory

4 arquivos

./

  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

src/

  • demo.tsdemo

Executar só Bun

  1. bun install# dependências
  2. bun run demo# roda o cenário

Saída: R$ 1.500,00 liquida por PIX com relatório BACEN (E00017700880000001) e $1,500.00 por SPEI com relatório Banxico (SPEI-7890-000002).

Requisitos
Bun

Código

src/demo.ts

// Demo: one checkout code runs in Brazil and Mexico; each region's factory creates a matching family — instant rail, currency formatter and regulator report.
type Transfer = { payerAccount: string; payeeKey: string; amountCents: number };

interface InterfacePaymentInstant {
  send(transfer: Transfer): string;
}
interface InterfaceFormatterCurrency {
  format(amountCents: number): string;
}
interface InterfaceReporterRegulator {
  report(transfer: Transfer, receipt: string): string;
}

// The abstract factory: one method per product of the family. A client holding a factory can never mix regions.
interface InterfaceFactoryRegion {
  paymentCreate(): InterfacePaymentInstant;
  formatterCreate(): InterfaceFormatterCurrency;
  reporterCreate(): InterfaceReporterRegulator;
}

// Fixed receipt sequence instead of a clock, so every run prints the same receipts.
let receiptSequence = 0;
const receiptNext = () => String(++receiptSequence).padStart(6, "0");

// Brazil family: PIX, reais, BACEN.
class PaymentInstantPix implements InterfacePaymentInstant {
  send(transfer: Transfer): string {
    return `E${transfer.payerAccount.replace("-", "")}${receiptNext()}`;
  }
}
class FormatterCurrencyBrl implements InterfaceFormatterCurrency {
  format(amountCents: number): string {
    return new Intl.NumberFormat("pt-BR", { style: "currency", currency: "BRL" }).format(amountCents / 100);
  }
}
class ReporterRegulatorBacen implements InterfaceReporterRegulator {
  report(transfer: Transfer, receipt: string): string {
    return `BACEN SPI ${receipt} payer=${transfer.payerAccount}`;
  }
}
class FactoryRegionBrazil implements InterfaceFactoryRegion {
  paymentCreate = () => new PaymentInstantPix();
  formatterCreate = () => new FormatterCurrencyBrl();
  reporterCreate = () => new ReporterRegulatorBacen();
}

// Mexico family: SPEI, pesos, Banxico.
class PaymentInstantSpei implements InterfacePaymentInstant {
  send(transfer: Transfer): string {
    return `SPEI-${transfer.payerAccount.slice(-4)}-${receiptNext()}`;
  }
}
class FormatterCurrencyMxn implements InterfaceFormatterCurrency {
  format(amountCents: number): string {
    return new Intl.NumberFormat("es-MX", { style: "currency", currency: "MXN" }).format(amountCents / 100);
  }
}
class ReporterRegulatorBanxico implements InterfaceReporterRegulator {
  report(transfer: Transfer, receipt: string): string {
    return `Banxico CEP ${receipt} ordenante=${transfer.payerAccount}`;
  }
}
class FactoryRegionMexico implements InterfaceFactoryRegion {
  paymentCreate = () => new PaymentInstantSpei();
  formatterCreate = () => new FormatterCurrencyMxn();
  reporterCreate = () => new ReporterRegulatorBanxico();
}

// The client only knows the factory interface: the same code serves every region.
function transferProcess(factory: InterfaceFactoryRegion, transfer: Transfer): string {
  const receipt = factory.paymentCreate().send(transfer);
  const amount = factory.formatterCreate().format(transfer.amountCents);
  return `${amount} → ${factory.reporterCreate().report(transfer, receipt)}`;
}

// The region is chosen once, at the composition root, from the account's country.
const FACTORIES: Record<"BR" | "MX", InterfaceFactoryRegion> = { BR: new FactoryRegionBrazil(), MX: new FactoryRegionMexico() };
for (const [country, transfer] of [
  ["BR", { payerAccount: "0001-7700880", payeeKey: "maria@banco.com", amountCents: 150_000 }],
  ["MX", { payerAccount: "012180001234567890", payeeKey: "646180157000000004", amountCents: 150_000 }],
] as const) {
  console.log(`  [${country}] ${transferProcess(FACTORIES[country], transfer)}`);
}

Relações

Onde ele se encaixa

Mapa
  1. Abstract Factory

    Por que se relacionam

    Próximo projeto, GoFAdapter
    Esc

    ↑ ↓ navegarEnter abrir239 resultados