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

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

Fluxo
4/4
FieldCurrencyPairMediatorExchangeOrderFieldAmounttotalbotão confirmarnotifynotifytotal em reaishabilita ou bloqueia
4

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

    FieldCurrencyPair e FieldAmount guardam o valor e chamam mediator.notify()

  2. 2

    Nenhum campo conhece outro

  3. 3

    MediatorExchangeOrder decide: cotação → total → botão

  4. 4

    Cotação com quatro casas em inteiros; total arredondado ao centavo

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

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

Por que se relacionam

Teste rápido

Qual destes combina com Mediator?

Próximo projeto, GoFMemento
Esc

↑ ↓ navegarEnter abrir239 resultados