pattern/gof/mediator
Mediator
Componentes interdependentes falam só com o mediador, que decide o efeito nos demais: a malha vira estrela. Use em formulários e painéis com campos interdependentes.
- passos
- 4
- arquivos
- 4
- testes
- 0
- tecnologias
- 2
Cenário
Ordem de câmbio: mudar o par ou o valor recalcula o total em reais e habilita ou não o botão de confirmar.
Planta
Fluxo4 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
Componentes interdependentes falam só com o mediador, que decide o efeito nos demais
Esconde cada passo: lembre antes de tocar para revelar.
- 1
FieldCurrencyPaireFieldAmountguardam o valor e chamammediator.notify() - 2
Nenhum campo conhece outro
- 3
MediatorExchangeOrderdecide: cotação → total → botão - 4
Cotação com quatro casas em inteiros; total arredondado ao centavo
Trade-offs
O que se ganha, o que se paga
Vantagens
Componentes sem referência entre si
Reação legível num lugar
Custos
Mediador concentra a lógica
Com muitos componentes vira classe-deus
Código
pattern/gof/mediator
4 arquivos./
- package.jsoninfra
- README.md
- tsconfig.jsoninfra
src/
- demo.tsdemo
Executar só Bun
bun run demo# roda o cenário
Saída: escolher USD/BRL deixa o total em R$ 0,00 e o botão desabilitado; digitar US$ 10.000,00 leva o total a R$ 54.321,00 e habilita o botão.
- Requisitos
- Bun
Código
src/demo.ts
// Demo: the customer fills an exchange order; each field only reports its change and the mediator updates the rest.
interface InterfaceOrderMediator {
notify(): void;
}
// Fields know only their mediator and report only their own change: no reference to another component.
class FieldCurrencyPair {
value = "";
constructor(private readonly mediator: InterfaceOrderMediator) {}
select(pair: string): void {
this.value = pair;
this.mediator.notify();
}
}
// Amount in cents of the foreign currency the customer buys.
class FieldAmount {
cents = 0;
constructor(private readonly mediator: InterfaceOrderMediator) {}
enter(amountCents: number): void {
this.cents = amountCents;
this.mediator.notify();
}
}
// Rates with four decimals as integers (5.4321 → 54_321): no float in the money path.
const QUOTES_E4: Record<string, number> = { "USD/BRL": 54_321, "EUR/BRL": 59_870 };
// The only place that knows the chain reaction: quote → total in reais → confirm button.
class MediatorExchangeOrder implements InterfaceOrderMediator {
readonly pair = new FieldCurrencyPair(this);
readonly amount = new FieldAmount(this);
totalBrlCents: number | null = null;
confirmEnabled = false;
notify(): void {
const rateE4 = QUOTES_E4[this.pair.value];
this.totalBrlCents = rateE4 === undefined ? null : Math.round((this.amount.cents * rateE4) / 10_000);
this.confirmEnabled = this.totalBrlCents !== null && this.amount.cents > 0;
}
}
const order = new MediatorExchangeOrder();
const show = (action: string) => console.log(` ${action.padEnd(20)} total ${order.totalBrlCents === null ? "-" : `R$ ${(order.totalBrlCents / 100).toFixed(2)}`} · confirm ${order.confirmEnabled ? "enabled" : "disabled"}`);
order.pair.select("USD/BRL");
show("select USD/BRL");
order.amount.enter(1_000_000);
show("enter USD 10000.00");
Nível
introdutório
1/13
- Linhas de TypeScript
- 42
- Tipo
- A — código puro
Domínio financeiro
- Câmbio
Padrões do catálogo que implementa
- Mediator
Trilhapasso 5 de 11
GoF — comportamento
Por que se relacionam
Combina com
Alternativa a
Teste rápido
Qual destes combina com Mediator?
Um handler por requisição. Abrir Vertical Slice Architecture
Seu progresso
0/157 estudados
Fica salvo só neste navegador.