pattern/gof/strategy
Strategy
Cada forma de liquidar é uma classe com a mesma interface; o contexto delega sem saber qual estratégia recebeu. Use quando o algoritmo é escolhido de fora.
- passos
- 4
- arquivos
- 4
- testes
- 0
- tecnologias
- 2
Cenário
Pagamento de R$ 5.000,00 por PIX, TED ou boleto, cada um com tarifa e prazo próprios.
Planta
Fluxo6 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
Cada forma de liquidar é uma classe com a mesma interface e o contexto delega sem saber qual recebeu
Esconde cada passo: lembre antes de tocar para revelar.
- 1
InterfaceStrategySettlement.plandevolve tarifa e prazo - 2
Uma estratégia por trilho
- 3
STRATEGIES_SETTLEMENTresolve a escolha num mapa - 4
ContextPayment.strategySettroca e delega
Trade-offs
O que se ganha, o que se paga
Vantagens
Contexto sem
switchNovo método = classe + entrada no mapa
Custos
Uma classe por variação
Variação única não justifica
Código
pattern/gof/strategy
4 arquivos./
- package.jsoninfra
- README.md
- tsconfig.jsoninfra
src/
- demo.tsdemo
Executar só Bun
bun run demo# roda o cenário
Saída: R$ 5.000,00 por PIX sem tarifa e instantâneo, por TED com tarifa de R$ 10,90 no mesmo dia útil e por boleto com R$ 3,50 e vencimento em 3 dias.
- Requisitos
- Bun
Código
src/demo.ts
// Demo: one payment context, the settlement strategy swapped by the method the customer chose; the context never branches on it.
type PaymentMethod = "pix" | "ted" | "boleto";
type SettlementPlan = { feeCents: number; settlesIn: string };
interface InterfaceStrategySettlement {
plan(amountCents: number): SettlementPlan;
}
// One algorithm per method, each with its own fee and settlement time.
class StrategySettlementPix implements InterfaceStrategySettlement {
plan(): SettlementPlan {
return { feeCents: 0, settlesIn: "instant" };
}
}
class StrategySettlementTed implements InterfaceStrategySettlement {
plan(): SettlementPlan {
return { feeCents: 1_090, settlesIn: "same business day" };
}
}
class StrategySettlementBoleto implements InterfaceStrategySettlement {
plan(): SettlementPlan {
return { feeCents: 350, settlesIn: "when paid, due in 3 days" };
}
}
// Which strategy is the caller's choice, resolved once here; a fourth method is a new class and a new entry.
const STRATEGIES_SETTLEMENT: Record<PaymentMethod, InterfaceStrategySettlement> = {
pix: new StrategySettlementPix(),
ted: new StrategySettlementTed(),
boleto: new StrategySettlementBoleto(),
};
// The context holds a strategy and delegates; swapping the algorithm is swapping the object.
class ContextPayment {
constructor(private strategy: InterfaceStrategySettlement) {}
strategySet(strategy: InterfaceStrategySettlement): void {
this.strategy = strategy;
}
settle(amountCents: number): SettlementPlan {
return this.strategy.plan(amountCents);
}
}
const context = new ContextPayment(STRATEGIES_SETTLEMENT.pix);
for (const method of ["pix", "ted", "boleto"] as const) {
context.strategySet(STRATEGIES_SETTLEMENT[method]);
const plan = context.settle(500_000);
console.log(` [${method.toUpperCase().padEnd(6)}] R$ 5000.00 → fee R$ ${(plan.feeCents / 100).toFixed(2)}, settles ${plan.settlesIn}`);
}
Nível
introdutório
1/13
- Linhas de TypeScript
- 44
- Tipo
- A — código puro
Domínio financeiro
- PIX
- TED
- Boleto
- Liquidação
- Tarifa
Padrões do catálogo que implementa
- Strategy
Trilhapasso 9 de 11
GoF — comportamento
Por que se relacionam
Combina com
Teste rápido
Qual destes combina com Strategy?
A fábrica escolhe a estratégia certa. Abrir Factory Method
Seu progresso
0/157 estudados
Fica salvo só neste navegador.