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

Facade

Interface única na frente de vários subsistemas: uma chamada do cliente, chamadas paralelas aos serviços, uma resposta. Só esconde quantos serviços existem e onde estão.

passos
4
arquivos
5
testes
0
tecnologias
4

Cenário

O portal mostra conta e saldo, limite do cartão e investimentos com uma chamada em vez de três.

Planta

Fluxo
4/4
Portal do bancofacadeaccounts :4041cards :4042investments :4043GET /portal/:id/accounts/:id/credit/:id/positions?account=
4

4 passos — reproduza para seguir o fluxo

Como funciona

4passos

Interface única na frente de vários subsistemas, com chamadas paralelas e uma resposta

Esconde cada passo: lembre antes de tocar para revelar.

Vocabulário compartilhado

  1. 1

    Só a facade conhece os endereços

  2. 2

    Promise.all: latência da chamada mais lenta

  3. 3

    AbortSignal.timeout por chamada

  4. 4

    Só orquestra e agrega, sem regra

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Uma chamada, sem acoplamento a endereços

  • Latência da mais lenta, não da soma

Custos

  • Mais um ponto de falha

  • Resposta única serve mal canais diferentes (use BFF)

Código

pattern/gof/facade

5 arquivos

./

  • .env.exampleinfra
  • 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: 200 com conta (R$ 8.420,50 disponíveis), cartão (limite R$ 12.000,00, usado R$ 3.450,00) e duas posições de investimento numa resposta só.

Requisitos
Bun

Código

src/demo.ts

// Demo: the bank portal makes one call; the facade asks three subsystems in parallel and returns one response.
import { Elysia } from "elysia";

// The subsystems only the facade knows, each its own HTTP service with its own route shape.
const URLS = { accounts: Bun.env.FACADE_ACCOUNTS_URL ?? "http://localhost:4041", cards: Bun.env.FACADE_CARDS_URL ?? "http://localhost:4042", investments: Bun.env.FACADE_INVESTMENTS_URL ?? "http://localhost:4043" };
const port = (url: string) => new URL(url).port;
const subsystems = [
  new Elysia().get("/accounts/:id", () => ({ holderName: "Ana Beatriz Costa", availableCents: 842_050 })).listen(port(URLS.accounts)),
  new Elysia().get("/credit/:id", () => ({ limitCents: 1_200_000, usedCents: 345_000, invoiceDueOn: "2026-10-15" })).listen(port(URLS.cards)),
  new Elysia().get("/positions", () => [{ product: "CDB 110% CDI", amountCents: 2_000_000 }, { product: "Tesouro Selic 2029", amountCents: 1_520_000 }]).listen(port(URLS.investments)),
];

// Each call carries its own timeout: a slow subsystem fails fast instead of holding the portal.
const FACADE_SUBSYSTEM_TIMEOUT_MS = 800;
async function subsystemGet(url: string): Promise<unknown> {
  const response = await fetch(url, { signal: AbortSignal.timeout(FACADE_SUBSYSTEM_TIMEOUT_MS) });
  if (!response.ok) throw new Error(`${url} answered ${response.status}`);
  return response.json();
}

// The facade orchestrates and aggregates only: latency is the slowest call, not the sum; every value comes as is.
const facade = new Elysia().get("/portal/:accountId", async ({ params: { accountId } }) => {
  const [account, credit, positions] = await Promise.all([subsystemGet(`${URLS.accounts}/accounts/${accountId}`), subsystemGet(`${URLS.cards}/credit/${accountId}`), subsystemGet(`${URLS.investments}/positions?account=${accountId}`)]);
  return { account, credit, positions };
});

const response = await facade.handle(new Request("http://localhost/portal/CC-0042"));
console.log(`  [PORTAL] GET /portal/CC-0042 → ${response.status} ${await response.text()}`);
await Promise.all(subsystems.map((subsystem) => subsystem.stop(true)));

Nível

introdutório

0/13

Linhas de TypeScript
25
Tipo
A — código puro

Domínio financeiro

  • Cartão
  • Conta corrente
  • Saldo
  • Investimentos
  • Limite

Padrões do catálogo que implementa

  • Facade

Variáveis de ambiente

FACADE_ACCOUNTS_URL
http://localhost:4041
Subsystems behind the facade, simulated in the same process.
FACADE_CARDS_URL
http://localhost:4042
FACADE_INVESTMENTS_URL
http://localhost:4043

Trilhapasso 5 de 7

GoF — estrutura

  1. 1Adapter
  2. 2Bridge
  3. 3Composite
  4. 4Decorator
  5. 5Facade
  6. 6Flyweight
  7. 7Proxy

Por que se relacionam

Teste rápido

Qual destes combina com Facade?

Próximo projeto, GoFFactory Method
Esc

↑ ↓ navegarEnter abrir239 resultados